diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-01-04 14:17:57 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-01-05 10:05:06 +0000 |
commit | 39d357e3248f80abea0159765ff39554affb40db (patch) | |
tree | aba0e6bfb76de0244bba0f5fdbd64b830dd6e621 /chromium/content/common | |
parent | 87778abf5a1f89266f37d1321b92a21851d8244d (diff) | |
download | qtwebengine-chromium-39d357e3248f80abea0159765ff39554affb40db.tar.gz |
BASELINE: Update Chromium to 55.0.2883.105
And updates ninja to 1.7.2
Change-Id: I20d43c737f82764d857ada9a55586901b18b9243
Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/content/common')
205 files changed, 5057 insertions, 3520 deletions
diff --git a/chromium/content/common/BUILD.gn b/chromium/content/common/BUILD.gn index d829dc56500..62b1a8f3793 100644 --- a/chromium/content/common/BUILD.gn +++ b/chromium/content/common/BUILD.gn @@ -4,7 +4,6 @@ import("//build/config/features.gni") import("//build/config/ui.gni") -import("//content/common/common.gni") import("//media/media_options.gni") import("//mojo/public/tools/bindings/mojom.gni") import("//tools/ipc_fuzzer/ipc_fuzzer.gni") @@ -19,34 +18,354 @@ source_set("common") { # build. visibility = [ "//content/*" ] - sources = rebase_path(content_common_gypi_values.private_common_sources, - ".", - "//content") + sources = [ + "accessibility_messages.h", + "all_messages.h", + "android/address_parser.cc", + "android/address_parser.h", + "android/address_parser_internal.cc", + "android/address_parser_internal.h", + "android/common_jni_registrar.cc", + "android/common_jni_registrar.h", + "android/gin_java_bridge_errors.cc", + "android/gin_java_bridge_errors.h", + "android/gin_java_bridge_value.cc", + "android/gin_java_bridge_value.h", + "android/hash_set.cc", + "android/hash_set.h", + "android/media_metadata_android.cc", + "android/media_metadata_android.h", + "android/resource_request_body_android.cc", + "android/resource_request_body_android.h", + "android/sync_compositor_messages.cc", + "android/sync_compositor_messages.h", + "android/sync_compositor_statics.cc", + "android/sync_compositor_statics.h", + "appcache_interfaces.cc", + "appcache_interfaces.h", + "appcache_messages.h", + "associated_interface_provider_impl.cc", + "associated_interface_provider_impl.h", + "associated_interface_registry_impl.cc", + "associated_interface_registry_impl.h", + "ax_content_node_data.cc", + "ax_content_node_data.h", + "bluetooth/web_bluetooth_device_id.cc", + "bluetooth/web_bluetooth_device_id.h", + "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", + "child_process_host_impl.h", + "child_process_messages.h", + "child_process_sandbox_support_impl_linux.cc", + "child_process_sandbox_support_impl_linux.h", + "child_process_sandbox_support_impl_shm_linux.cc", + "clipboard_format.h", + "clipboard_messages.h", + "content_constants_internal.cc", + "content_constants_internal.h", + "content_export.h", + "content_ipc_logging.cc", + "content_message_generator.cc", + "content_message_generator.h", + "content_param_traits.cc", + "content_param_traits.h", + "content_param_traits_macros.h", + "content_paths.cc", + "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", + "cursors/webcursor_aura.cc", + "cursors/webcursor_aurawin.cc", + "cursors/webcursor_aurax11.cc", + "cursors/webcursor_mac.mm", + "cursors/webcursor_ozone.cc", + "database_messages.h", + "date_time_suggestion.h", + "device_sensors/device_light_data.h", + "device_sensors/device_light_hardware_buffer.h", + "device_sensors/device_motion_hardware_buffer.h", + "device_sensors/device_orientation_hardware_buffer.h", + "devtools_messages.h", + "discardable_shared_memory_heap.cc", + "discardable_shared_memory_heap.h", + "dom_storage/dom_storage_map.cc", + "dom_storage/dom_storage_map.h", + "dom_storage/dom_storage_messages.h", + "drag_event_source_info.h", + "drag_messages.h", + "drag_traits.h", + "dwrite_font_proxy_messages.h", + "edit_command.h", + "establish_channel_params.cc", + "establish_channel_params.h", + "file_utilities_messages.h", + "fileapi/file_system_messages.h", + "font_cache_dispatcher_win.cc", + "font_cache_dispatcher_win.h", + "font_config_ipc_linux.cc", + "font_config_ipc_linux.h", + "font_list.cc", + "font_list.h", + "font_list_android.cc", + "font_list_fontconfig.cc", + "font_list_mac.mm", + "font_list_win.cc", + "frame_message_enums.h", + "frame_messages.h", + "frame_owner_properties.cc", + "frame_owner_properties.h", + "frame_replication_state.cc", + "frame_replication_state.h", + "gamepad_hardware_buffer.h", + "gamepad_messages.h", + "gamepad_param_traits.cc", + "gamepad_param_traits.h", + "generic_shared_memory_id_generator.cc", + "generic_shared_memory_id_generator.h", + "gin_java_bridge_messages.h", + "gpu/client/command_buffer_metrics.cc", + "gpu/client/command_buffer_metrics.h", + "gpu/client/context_provider_command_buffer.cc", + "gpu/client/context_provider_command_buffer.h", + "gpu_host_messages.h", + "host_discardable_shared_memory_manager.cc", + "host_discardable_shared_memory_manager.h", + "host_shared_bitmap_manager.cc", + "host_shared_bitmap_manager.h", + "in_process_child_thread_params.cc", + "in_process_child_thread_params.h", + "indexed_db/indexed_db_constants.h", + "indexed_db/indexed_db_key.cc", + "indexed_db/indexed_db_key.h", + "indexed_db/indexed_db_key_path.cc", + "indexed_db/indexed_db_key_path.h", + "indexed_db/indexed_db_key_range.cc", + "indexed_db/indexed_db_key_range.h", + "indexed_db/indexed_db_messages.h", + "indexed_db/indexed_db_param_traits.cc", + "indexed_db/indexed_db_param_traits.h", + "input/event_with_latency_info.cc", + "input/event_with_latency_info.h", + "input/gesture_event_stream_validator.cc", + "input/gesture_event_stream_validator.h", + "input/input_event.cc", + "input/input_event.h", + "input/input_event_ack.cc", + "input/input_event_ack.h", + "input/input_event_dispatch_type.h", + "input/input_event_stream_validator.cc", + "input/input_event_stream_validator.h", + "input/input_param_traits.cc", + "input/input_param_traits.h", + "input/synthetic_gesture_packet.cc", + "input/synthetic_gesture_packet.h", + "input/synthetic_gesture_params.cc", + "input/synthetic_gesture_params.h", + "input/synthetic_pinch_gesture_params.cc", + "input/synthetic_pinch_gesture_params.h", + "input/synthetic_pointer_action_params.cc", + "input/synthetic_pointer_action_params.h", + "input/synthetic_smooth_drag_gesture_params.cc", + "input/synthetic_smooth_drag_gesture_params.h", + "input/synthetic_smooth_scroll_gesture_params.cc", + "input/synthetic_smooth_scroll_gesture_params.h", + "input/synthetic_tap_gesture_params.cc", + "input/synthetic_tap_gesture_params.h", + "input/synthetic_web_input_event_builders.cc", + "input/synthetic_web_input_event_builders.h", + "input/touch_event_stream_validator.cc", + "input/touch_event_stream_validator.h", + "input/web_input_event_queue.h", + "input/web_touch_event_traits.cc", + "input/web_touch_event_traits.h", + "input_messages.h", + "inter_process_time_ticks_converter.cc", + "inter_process_time_ticks_converter.h", + "layer_tree_settings_factory.cc", + "layer_tree_settings_factory.h", + "mac/attributed_string_coder.h", + "mac/attributed_string_coder.mm", + "mac/font_descriptor.h", + "mac/font_descriptor.mm", + "mac/font_loader.h", + "mac/font_loader.mm", + "manifest_manager_messages.h", + "media/aec_dump_messages.h", + "media/audio_messages.h", + "media/cdm_info.cc", + "media/cdm_messages.h", + "media/cdm_messages_enums.h", + "media/media_devices.cc", + "media/media_devices.h", + "media/media_metadata_sanitizer.cc", + "media/media_metadata_sanitizer.h", + "media/media_player_delegate_messages.h", + "media/media_player_messages_android.h", + "media/media_stream_messages.h", + "media/media_stream_options.cc", + "media/media_stream_options.h", + "media/media_stream_track_metrics_host_messages.h", + "media/midi_messages.h", + "media/surface_view_manager_messages_android.h", + "media/video_capture.h", + "media/video_capture_messages.h", + "memory_messages.h", + "message_port_messages.h", + "navigation_gesture.h", + "navigation_params.cc", + "navigation_params.h", + "net/url_fetcher.cc", + "net/url_request_service_worker_data.cc", + "net/url_request_service_worker_data.h", + "net/url_request_user_data.cc", + "net/url_request_user_data.h", + "origin_trials/trial_token.cc", + "origin_trials/trial_token.h", + "origin_trials/trial_token_validator.cc", + "origin_trials/trial_token_validator.h", + "origin_util.cc", + "p2p_messages.h", + "page_state_serialization.cc", + "page_state_serialization.h", + "page_zoom.cc", + "pepper_file_util.cc", + "pepper_file_util.h", + "pepper_plugin_list.cc", + "pepper_plugin_list.h", + "pepper_renderer_instance_data.cc", + "pepper_renderer_instance_data.h", + "platform_notification_messages.h", + "plugin_list.cc", + "plugin_list.h", + "power_monitor_messages.h", + "process_type.cc", + "push_messaging_messages.h", + "quota_messages.h", + "render_process_messages.h", + "resize_params.cc", + "resize_params.h", + "resource_messages.cc", + "resource_messages.h", + "resource_request.cc", + "resource_request.h", + "resource_request_body_impl.cc", + "resource_request_body_impl.h", + "resource_request_completion_status.cc", + "resource_request_completion_status.h", + "sandbox_init_mac.cc", + "sandbox_init_mac.h", + "sandbox_init_win.cc", + "sandbox_linux/android/sandbox_bpf_base_policy_android.cc", + "sandbox_linux/android/sandbox_bpf_base_policy_android.h", + "sandbox_linux/bpf_cros_arm_gpu_policy_linux.cc", + "sandbox_linux/bpf_cros_arm_gpu_policy_linux.h", + "sandbox_linux/bpf_gpu_policy_linux.cc", + "sandbox_linux/bpf_gpu_policy_linux.h", + "sandbox_linux/bpf_ppapi_policy_linux.cc", + "sandbox_linux/bpf_ppapi_policy_linux.h", + "sandbox_linux/bpf_renderer_policy_linux.cc", + "sandbox_linux/bpf_renderer_policy_linux.h", + "sandbox_linux/bpf_utility_policy_linux.cc", + "sandbox_linux/bpf_utility_policy_linux.h", + "sandbox_linux/sandbox_bpf_base_policy_linux.cc", + "sandbox_linux/sandbox_bpf_base_policy_linux.h", + "sandbox_linux/sandbox_debug_handling_linux.cc", + "sandbox_linux/sandbox_debug_handling_linux.h", + "sandbox_linux/sandbox_init_linux.cc", + "sandbox_linux/sandbox_linux.cc", + "sandbox_linux/sandbox_linux.h", + "sandbox_linux/sandbox_seccomp_bpf_linux.cc", + "sandbox_linux/sandbox_seccomp_bpf_linux.h", + "sandbox_mac.h", + "sandbox_mac.mm", + "sandbox_win.cc", + "sandbox_win.h", + "savable_subframe.h", + "savable_url_schemes.cc", + "savable_url_schemes.h", + "screen_orientation_messages.h", + "security_style_util.cc", + "security_style_util.h", + "send_zygote_child_ping_linux.cc", + "service_manager/embedded_service_runner.cc", + "service_manager/embedded_service_runner.h", + "service_manager/service_manager_connection_impl.cc", + "service_manager/service_manager_connection_impl.h", + "service_worker/embedded_worker_messages.h", + "service_worker/embedded_worker_settings.h", + "service_worker/embedded_worker_start_params.cc", + "service_worker/embedded_worker_start_params.h", + "service_worker/service_worker_client_info.cc", + "service_worker/service_worker_client_info.h", + "service_worker/service_worker_messages.h", + "service_worker/service_worker_status_code.cc", + "service_worker/service_worker_status_code.h", + "service_worker/service_worker_type_converters.cc", + "service_worker/service_worker_type_converters.h", + "service_worker/service_worker_types.cc", + "service_worker/service_worker_types.h", + "service_worker/service_worker_utils.cc", + "service_worker/service_worker_utils.h", + "set_process_title.cc", + "set_process_title.h", + "set_process_title_linux.cc", + "set_process_title_linux.h", + "site_isolation_policy.cc", + "site_isolation_policy.h", + "speech_recognition_messages.h", + "swapped_out_messages.cc", + "swapped_out_messages.h", + "text_input_client_messages.h", + "text_input_state.cc", + "text_input_state.h", + "url_schemes.cc", + "url_schemes.h", + "user_agent.cc", + "utility_messages.h", + "view_message_enums.h", + "view_messages.h", + "worker_messages.h", + "zygote_commands_linux.h", + ] configs += [ "//content:content_implementation", "//build/config:precompiled_headers", "//build/config/compiler:no_size_t_to_int_warning", + "//media/gpu:gpu_config", ] public_deps = [ ":mojo_bindings", + "//cc", "//gpu/command_buffer/common", "//ipc", "//third_party/WebKit/public:blink_headers", ] deps = [ + # This looks needless as we have :mojo_bindings in public_deps, but it's + # needed because of allow_circular_includes_from. + ":mojo_bindings_cpp_sources", "//base", "//base/third_party/dynamic_annotations", "//build/util:webkit_version", - "//cc", "//cc/ipc", "//cc/surfaces", - "//components/mus/public/interfaces", "//components/tracing", "//components/tracing:startup_tracing", "//content:resources", "//content/app/resources", + "//device/base/synchronization", "//device/bluetooth", "//gpu", "//gpu/command_buffer/client:gles2_c_lib", @@ -59,6 +378,7 @@ source_set("common") { "//gpu/ipc/common", "//gpu/skia_bindings", "//ipc", + "//ipc:mojom", "//media", "//media:shared_memory_support", "//media/base/ipc", @@ -74,6 +394,7 @@ source_set("common") { "//services/shell/public/cpp", "//services/shell/public/interfaces", "//services/shell/runner/common", + "//services/ui/public/interfaces", "//skia", "//storage/common", "//third_party/WebKit/public:blink_minimal", @@ -85,10 +406,12 @@ source_set("common") { "//ui/base", "//ui/base/ime", "//ui/display", + "//ui/events/blink", "//ui/events/ipc", "//ui/gfx", "//ui/gfx/geometry", "//ui/gfx/ipc", + "//ui/gfx/ipc/color", "//ui/gfx/ipc/geometry", "//ui/gfx/ipc/skia", "//ui/gl", @@ -102,6 +425,8 @@ source_set("common") { libs = [] ldflags = [] + allow_circular_includes_from = [ ":mojo_bindings_cpp_sources" ] + if (is_android && use_seccomp_bpf) { set_sources_assignment_filter([]) sources += [ @@ -134,10 +459,7 @@ source_set("common") { if (use_ozone) { deps += [ "//ui/ozone" ] } else { - sources -= [ - "cursors/webcursor_ozone.cc", - "font_list_ozone.cc", - ] + sources -= [ "cursors/webcursor_ozone.cc" ] } if (!use_aura || is_android) { @@ -148,15 +470,12 @@ source_set("common") { sources -= [ "cursors/webcursor_aurax11.cc" ] } - if (use_pango) { - configs += [ "//build/config/linux/pangocairo" ] - if (use_ozone) { - # If we're using pango, never use this ozone file (it was removed in all - # non-ozone cases above). - sources -= [ "font_list_ozone.cc" ] - } - } else { - sources -= [ "font_list_pango.cc" ] + if (is_linux) { + deps += [ "//build/linux:fontconfig" ] + } + + if (is_mac || is_win || is_android) { + sources -= [ "font_list_fontconfig.cc" ] } if (enable_plugins) { @@ -232,32 +551,49 @@ group("for_content_tests") { } mojom("mojo_bindings") { - # This interface is internal to content. However, this is not exported from - # the content component shared library. Code in content but outside of the - # content component (content/test or content/shell) should link to this - # directly. + # This interface is internal to content. visibility = [ "//content/*" ] sources = [ + "associated_interfaces.mojom", + "child_memory_coordinator.mojom", "frame.mojom", "image_downloader/image_downloader.mojom", "leveldb_wrapper.mojom", - "process_control.mojom", + "memory_coordinator.mojom", + "native_types.mojom", + "render_frame_message_filter.mojom", + "render_message_filter.mojom", "render_widget_window_tree_client_factory.mojom", + "renderer.mojom", + "service_worker/embedded_worker.mojom", "service_worker/embedded_worker_setup.mojom", "storage_partition_service.mojom", + "url_loader.mojom", + "url_loader_factory.mojom", + "video_capture.mojom", ] import_dirs = [ "//mojo/services" ] public_deps = [ "//components/leveldb/public/interfaces", - "//components/mus/public/interfaces", + "//content/public/common:interfaces", + "//device/sensors/public/interfaces", + "//ipc:mojom", "//services/shell/public/interfaces", + "//services/ui/public/interfaces", "//skia/public/interfaces", "//third_party/WebKit/public:mojo_bindings", + "//third_party/WebKit/public:new_wrapper_types_mojo_bindings", + "//ui/base/mojo:mojo_bindings", "//ui/gfx/geometry/mojo", + "//ui/gfx/mojo", "//url/mojo:url_mojom_gurl", "//url/mojo:url_mojom_origin", ] + + export_class_attribute = "CONTENT_EXPORT" + export_define = "CONTENT_IMPLEMENTATION=1" + export_header = "content/common/content_export.h" } diff --git a/chromium/content/common/DEPS b/chromium/content/common/DEPS index ad4b6f0228a..4b53a47874f 100644 --- a/chromium/content/common/DEPS +++ b/chromium/content/common/DEPS @@ -1,6 +1,9 @@ include_rules = [ "-storage/browser", + "+device/base/synchronization", + "+services/shell/public/cpp", + # No inclusion of WebKit from the browser, other than strictly enum/POD, # header-only types, and some selected common code. "-third_party/WebKit", @@ -24,11 +27,13 @@ include_rules = [ "+third_party/WebKit/public/platform/WebStorageArea.h", "+third_party/WebKit/public/platform/linux/WebFallbackFont.h", "+third_party/WebKit/public/platform/linux/WebFontRenderStyle.h", - "+third_party/WebKit/public/platform/modules/bluetooth/WebBluetoothError.h", + "+third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.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/indexeddb/WebIDBTypes.h", + "+third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h", "+third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h", + "+third_party/WebKit/public/platform/modules/permissions/WebPermissionType.h", "+third_party/WebKit/public/platform/modules/push_messaging/WebPushError.h", "+third_party/WebKit/public/platform/modules/push_messaging/WebPushPermissionStatus.h", "+third_party/WebKit/public/platform/modules/screen_orientation/WebLockOrientationError.h", diff --git a/chromium/content/common/OWNERS b/chromium/content/common/OWNERS index 77241690419..fe97f93303a 100644 --- a/chromium/content/common/OWNERS +++ b/chromium/content/common/OWNERS @@ -36,11 +36,6 @@ per-file *.mojom=file://ipc/SECURITY_OWNERS per-file accessibility_node_data.*=dmazzoni@chromium.org per-file accessibility_node_data.*=dtseng@chromium.org -# WebSocket -per-file websocket.*=ricea@chromium.org -per-file websocket.*=tyoshino@chromium.org -per-file websocket.*=yhirano@chromium.org - # DirectWrite per-file dwrite_font_platform_win*=scottmg@chromium.org per-file font_warmup_win.cc=scottmg@chromium.org diff --git a/chromium/content/common/accessibility_messages.h b/chromium/content/common/accessibility_messages.h index cbb3ca963e8..abb97a739d7 100644 --- a/chromium/content/common/accessibility_messages.h +++ b/chromium/content/common/accessibility_messages.h @@ -14,6 +14,7 @@ #include "ipc/param_traits_macros.h" #include "third_party/WebKit/public/web/WebAXEnums.h" #include "ui/accessibility/ax_node_data.h" +#include "ui/accessibility/ax_relative_bounds.h" #include "ui/accessibility/ax_tree_update.h" #include "ui/gfx/transform.h" @@ -39,6 +40,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::AXContentNodeData) IPC_STRUCT_TRAITS_MEMBER(html_attributes) IPC_STRUCT_TRAITS_MEMBER(child_ids) IPC_STRUCT_TRAITS_MEMBER(content_int_attributes) + IPC_STRUCT_TRAITS_MEMBER(offset_container_id) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::AXContentTreeData) @@ -54,8 +56,10 @@ IPC_STRUCT_TRAITS_BEGIN(content::AXContentTreeData) IPC_STRUCT_TRAITS_MEMBER(focus_id) IPC_STRUCT_TRAITS_MEMBER(sel_anchor_object_id) IPC_STRUCT_TRAITS_MEMBER(sel_anchor_offset) + IPC_STRUCT_TRAITS_MEMBER(sel_anchor_affinity) IPC_STRUCT_TRAITS_MEMBER(sel_focus_object_id) IPC_STRUCT_TRAITS_MEMBER(sel_focus_offset) + IPC_STRUCT_TRAITS_MEMBER(sel_focus_affinity) IPC_STRUCT_TRAITS_MEMBER(routing_id) IPC_STRUCT_TRAITS_MEMBER(parent_routing_id) IPC_STRUCT_TRAITS_END() @@ -77,15 +81,17 @@ IPC_STRUCT_BEGIN(AccessibilityHostMsg_EventParams) // ID of the node that the event applies to. IPC_STRUCT_MEMBER(int, id) + + // The source of this event. + IPC_STRUCT_MEMBER(ui::AXEventFrom, event_from) IPC_STRUCT_END() IPC_STRUCT_BEGIN(AccessibilityHostMsg_LocationChangeParams) // ID of the object whose location is changing. IPC_STRUCT_MEMBER(int, id) - // The object's new location, in frame-relative coordinates (same - // as the coordinates in AccessibilityNodeData). - IPC_STRUCT_MEMBER(gfx::Rect, new_location) + // The object's new location info. + IPC_STRUCT_MEMBER(ui::AXRelativeBounds, new_location) IPC_STRUCT_END() IPC_STRUCT_BEGIN(AccessibilityHostMsg_FindInPageResultParams) @@ -178,8 +184,10 @@ IPC_MESSAGE_ROUTED1(AccessibilityMsg_SetAccessibilityFocus, int /* object id */) // Tells the render view that a AccessibilityHostMsg_Events -// message was processed and it can send addition events. -IPC_MESSAGE_ROUTED0(AccessibilityMsg_Events_ACK) +// message was processed and it can send additional events. The argument +// must be the same as the ack_token passed to AccessibilityHostMsg_Events. +IPC_MESSAGE_ROUTED1(AccessibilityMsg_Events_ACK, + int /* ack_token */) // Tell the renderer to reset and send a new accessibility tree from // scratch because the browser is out of sync. It passes a sequential @@ -204,15 +212,17 @@ IPC_MESSAGE_ROUTED1(AccessibilityMsg_SnapshotTree, // Messages sent from the renderer to the browser. // Sent to notify the browser about renderer accessibility events. -// The browser responds with a AccessibilityMsg_Events_ACK. +// The browser responds with a AccessibilityMsg_Events_ACK with the same +// ack_token. // The second parameter, reset_token, is set if this IPC was sent in response // to a reset request from the browser. When the browser requests a reset, // it ignores incoming IPCs until it sees one with the correct reset token. // Any other time, it ignores IPCs with a reset token. -IPC_MESSAGE_ROUTED2( +IPC_MESSAGE_ROUTED3( AccessibilityHostMsg_Events, std::vector<AccessibilityHostMsg_EventParams> /* events */, - int /* reset_token */) + int /* reset_token */, + int /* ack_token */) // Sent to update the browser of the location of accessibility objects. IPC_MESSAGE_ROUTED1( diff --git a/chromium/content/common/android/OWNERS b/chromium/content/common/android/OWNERS index 9e94ab23248..21f1e244ff0 100644 --- a/chromium/content/common/android/OWNERS +++ b/chromium/content/common/android/OWNERS @@ -1,3 +1,5 @@ +aelias@chromium.org +boliu@chromium.org tedchoc@chromium.org yfriedman@chromium.org diff --git a/chromium/content/common/android/hash_set.cc b/chromium/content/common/android/hash_set.cc index bd73b779734..4e6839b7cb3 100644 --- a/chromium/content/common/android/hash_set.cc +++ b/chromium/content/common/android/hash_set.cc @@ -6,25 +6,21 @@ namespace content { -bool RegisterHashSet(JNIEnv* env) { - return JNI_HashSet::RegisterNativesImpl(env); -} - void JNI_Java_HashSet_add(JNIEnv* env, const base::android::JavaRef<jobject>& hash_set, const base::android::JavaRef<jobject>& object) { - JNI_HashSet::Java_HashSet_add(env, hash_set.obj(), object.obj()); + JNI_HashSet::Java_HashSet_add(env, hash_set, object); } void JNI_Java_HashSet_remove(JNIEnv* env, const base::android::JavaRef<jobject>& hash_set, const base::android::JavaRef<jobject>& object) { - JNI_HashSet::Java_HashSet_remove(env, hash_set.obj(), object.obj()); + JNI_HashSet::Java_HashSet_remove(env, hash_set, object); } void JNI_Java_HashSet_clear(JNIEnv* env, const base::android::JavaRef<jobject>& hash_set) { - JNI_HashSet::Java_HashSet_clear(env, hash_set.obj()); + JNI_HashSet::Java_HashSet_clear(env, hash_set); } } // namespace content diff --git a/chromium/content/common/android/hash_set.h b/chromium/content/common/android/hash_set.h index b7a58707847..f2034f7ce80 100644 --- a/chromium/content/common/android/hash_set.h +++ b/chromium/content/common/android/hash_set.h @@ -8,8 +8,6 @@ namespace content { -bool RegisterHashSet(JNIEnv* env); - void JNI_Java_HashSet_add(JNIEnv* env, const base::android::JavaRef<jobject>& hash_set, const base::android::JavaRef<jobject>& object); diff --git a/chromium/content/common/android/media_metadata_android.cc b/chromium/content/common/android/media_metadata_android.cc index 0bd15631758..9238b867a32 100644 --- a/chromium/content/common/android/media_metadata_android.cc +++ b/chromium/content/common/android/media_metadata_android.cc @@ -4,12 +4,32 @@ #include "content/common/android/media_metadata_android.h" +#include <string> +#include <vector> + +#include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "content/public/common/media_metadata.h" #include "jni/MediaMetadata_jni.h" +using base::android::ScopedJavaLocalRef; + namespace content { +namespace { + +std::vector<int> GetFlattenedSizeArray(const std::vector<gfx::Size>& sizes) { + std::vector<int> flattened_array; + flattened_array.reserve(2 * sizes.size()); + for (const auto& size : sizes) { + flattened_array.push_back(size.width()); + flattened_array.push_back(size.height()); + } + return flattened_array; +} + +} // anonymous namespace + // static base::android::ScopedJavaLocalRef<jobject> MediaMetadataAndroid::CreateJavaObject( @@ -21,13 +41,24 @@ MediaMetadataAndroid::CreateJavaObject( ScopedJavaLocalRef<jstring> j_album( base::android::ConvertUTF16ToJavaString(env, metadata.album)); - return Java_MediaMetadata_create( - env, j_title.obj(), j_artist.obj(), j_album.obj()); -} + ScopedJavaLocalRef<jobject> j_metadata = + Java_MediaMetadata_create(env, j_title, j_artist, j_album); -// static -bool MediaMetadataAndroid::Register(JNIEnv* env) { - return RegisterNativesImpl(env); + for (const auto& artwork : metadata.artwork) { + std::string src = artwork.src.spec(); + ScopedJavaLocalRef<jstring> j_src( + base::android::ConvertUTF8ToJavaString(env, src)); + ScopedJavaLocalRef<jstring> j_type( + base::android::ConvertUTF16ToJavaString(env, artwork.type)); + ScopedJavaLocalRef<jintArray> j_sizes( + base::android::ToJavaIntArray( + env, GetFlattenedSizeArray(artwork.sizes))); + + Java_MediaMetadata_createAndAddArtwork(env, j_metadata, j_src, j_type, + j_sizes); + } + + return j_metadata; } } // namespace content diff --git a/chromium/content/common/android/media_metadata_android.h b/chromium/content/common/android/media_metadata_android.h index e580e53af0f..7dc92a2f97a 100644 --- a/chromium/content/common/android/media_metadata_android.h +++ b/chromium/content/common/android/media_metadata_android.h @@ -18,8 +18,6 @@ class MediaMetadataAndroid { static base::android::ScopedJavaLocalRef<jobject> CreateJavaObject( JNIEnv* env, const MediaMetadata& metadata); - static bool Register(JNIEnv* env); - private: DISALLOW_IMPLICIT_CONSTRUCTORS(MediaMetadataAndroid); }; diff --git a/chromium/content/common/android/resource_request_body_android.cc b/chromium/content/common/android/resource_request_body_android.cc index 3f91c9a1d36..7abf4e8ceeb 100644 --- a/chromium/content/common/android/resource_request_body_android.cc +++ b/chromium/content/common/android/resource_request_body_android.cc @@ -15,6 +15,8 @@ #include "content/public/common/resource_request_body.h" #include "jni/ResourceRequestBody_jni.h" +using base::android::JavaParamRef; + namespace content { namespace { @@ -64,8 +66,7 @@ ConvertResourceRequestBodyToJavaObject( base::android::ScopedJavaLocalRef<jbyteArray> j_encoded = ConvertResourceRequestBodyToJavaArray(env, *body); - return Java_ResourceRequestBody_createFromEncodedNativeForm(env, - j_encoded.obj()); + return Java_ResourceRequestBody_createFromEncodedNativeForm(env, j_encoded); } scoped_refptr<ResourceRequestBodyImpl> ExtractResourceRequestBodyFromJavaObject( @@ -75,7 +76,7 @@ scoped_refptr<ResourceRequestBodyImpl> ExtractResourceRequestBodyFromJavaObject( return nullptr; base::android::ScopedJavaLocalRef<jbyteArray> j_encoded = - Java_ResourceRequestBody_getEncodedNativeForm(env, j_body.obj()); + Java_ResourceRequestBody_getEncodedNativeForm(env, j_body); if (j_encoded.is_null()) return nullptr; diff --git a/chromium/content/common/android/sync_compositor_messages.cc b/chromium/content/common/android/sync_compositor_messages.cc index f9be4b274ff..cf2e31b0175 100644 --- a/chromium/content/common/android/sync_compositor_messages.cc +++ b/chromium/content/common/android/sync_compositor_messages.cc @@ -9,16 +9,10 @@ namespace content { SyncCompositorDemandDrawHwParams::SyncCompositorDemandDrawHwParams() {} SyncCompositorDemandDrawHwParams::SyncCompositorDemandDrawHwParams( - const gfx::Size& surface_size, - const gfx::Transform& transform, - const gfx::Rect& viewport, - const gfx::Rect& clip, + const gfx::Size& viewport_size, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) - : surface_size(surface_size), - transform(transform), - viewport(viewport), - clip(clip), + : viewport_size(viewport_size), viewport_rect_for_tile_priority(viewport_rect_for_tile_priority), transform_for_tile_priority(transform_for_tile_priority) {} @@ -31,15 +25,15 @@ SyncCompositorDemandDrawSwParams::SyncCompositorDemandDrawSwParams() {} SyncCompositorDemandDrawSwParams::~SyncCompositorDemandDrawSwParams() {} -SyncCompositorCommonRendererParams::SyncCompositorCommonRendererParams() - : version(0u), - page_scale_factor(0.f), - min_page_scale_factor(0.f), - max_page_scale_factor(0.f), - need_animate_scroll(false), - need_invalidate_count(0u), - did_activate_pending_tree_count(0u) {} +SyncCompositorCommonRendererParams::SyncCompositorCommonRendererParams() = + default; + +SyncCompositorCommonRendererParams::SyncCompositorCommonRendererParams( + const SyncCompositorCommonRendererParams& other) = default; SyncCompositorCommonRendererParams::~SyncCompositorCommonRendererParams() {} +SyncCompositorCommonRendererParams& SyncCompositorCommonRendererParams:: +operator=(const SyncCompositorCommonRendererParams& other) = default; + } // namespace content diff --git a/chromium/content/common/android/sync_compositor_messages.h b/chromium/content/common/android/sync_compositor_messages.h index 62eafb7200e..e7e41d6e5d0 100644 --- a/chromium/content/common/android/sync_compositor_messages.h +++ b/chromium/content/common/android/sync_compositor_messages.h @@ -7,10 +7,8 @@ #include "base/memory/shared_memory_handle.h" #include "cc/output/begin_frame_args.h" #include "cc/output/compositor_frame.h" -#include "cc/output/compositor_frame_ack.h" #include "content/common/content_export.h" #include "content/common/content_param_traits.h" -#include "content/common/input/did_overscroll_params.h" #include "content/common/input/input_event_ack_state.h" #include "ipc/ipc_message_macros.h" #include "third_party/WebKit/public/web/WebInputEvent.h" @@ -25,17 +23,12 @@ namespace content { struct SyncCompositorDemandDrawHwParams { SyncCompositorDemandDrawHwParams(); SyncCompositorDemandDrawHwParams( - const gfx::Size& surface_size, - const gfx::Transform& transform, - const gfx::Rect& viewport, - const gfx::Rect& clip, + const gfx::Size& viewport_size, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority); ~SyncCompositorDemandDrawHwParams(); - gfx::Size surface_size; - gfx::Transform transform; - gfx::Rect viewport; + gfx::Size viewport_size; gfx::Rect clip; gfx::Rect viewport_rect_for_tile_priority; gfx::Transform transform_for_tile_priority; @@ -61,16 +54,22 @@ struct SyncCompositorCommonRendererParams { SyncCompositorCommonRendererParams(); ~SyncCompositorCommonRendererParams(); - unsigned int version; + // Allow copy. + SyncCompositorCommonRendererParams( + const SyncCompositorCommonRendererParams& other); + SyncCompositorCommonRendererParams& operator=( + const SyncCompositorCommonRendererParams& other); + + unsigned int version = 0u; gfx::ScrollOffset total_scroll_offset; gfx::ScrollOffset max_scroll_offset; gfx::SizeF scrollable_size; - float page_scale_factor; - float min_page_scale_factor; - float max_page_scale_factor; - bool need_animate_scroll; - uint32_t need_invalidate_count; - uint32_t did_activate_pending_tree_count; + float page_scale_factor = 0.f; + float min_page_scale_factor = 0.f; + float max_page_scale_factor = 0.f; + bool need_animate_scroll = false; + uint32_t need_invalidate_count = 0u; + uint32_t did_activate_pending_tree_count = 0u; }; } // namespace content @@ -84,10 +83,7 @@ struct SyncCompositorCommonRendererParams { #define IPC_MESSAGE_START SyncCompositorMsgStart IPC_STRUCT_TRAITS_BEGIN(content::SyncCompositorDemandDrawHwParams) - IPC_STRUCT_TRAITS_MEMBER(surface_size) - IPC_STRUCT_TRAITS_MEMBER(transform) - IPC_STRUCT_TRAITS_MEMBER(viewport) - IPC_STRUCT_TRAITS_MEMBER(clip) + IPC_STRUCT_TRAITS_MEMBER(viewport_size) IPC_STRUCT_TRAITS_MEMBER(viewport_rect_for_tile_priority) IPC_STRUCT_TRAITS_MEMBER(transform_for_tile_priority) IPC_STRUCT_TRAITS_END() @@ -120,16 +116,21 @@ IPC_STRUCT_TRAITS_END() // Synchronous IPCs are allowed here to the renderer compositor thread. See // design doc https://goo.gl/Tn81FW and crbug.com/526842 for details. -IPC_SYNC_MESSAGE_ROUTED0_1(SyncCompositorMsg_SynchronizeRendererState, - content::SyncCompositorCommonRendererParams) +IPC_SYNC_MESSAGE_CONTROL1_1( + SyncCompositorMsg_SynchronizeRendererState, + std::vector<int> /* routing ids*/, + std::vector<content::SyncCompositorCommonRendererParams>) IPC_MESSAGE_ROUTED1(SyncCompositorMsg_ComputeScroll, base::TimeTicks); +IPC_MESSAGE_ROUTED1(SyncCompositorMsg_DemandDrawHwAsync, + content::SyncCompositorDemandDrawHwParams) + IPC_SYNC_MESSAGE_ROUTED1_3(SyncCompositorMsg_DemandDrawHw, content::SyncCompositorDemandDrawHwParams, content::SyncCompositorCommonRendererParams, - uint32_t /* output_surface_id */, + uint32_t /* compositor_frame_sink_id */, cc::CompositorFrame) IPC_SYNC_MESSAGE_ROUTED1_2(SyncCompositorMsg_SetSharedMemory, @@ -154,15 +155,19 @@ IPC_MESSAGE_ROUTED1(SyncCompositorMsg_SetMemoryPolicy, uint32_t /* bytes_limit */); IPC_MESSAGE_ROUTED2(SyncCompositorMsg_ReclaimResources, - uint32_t /* output_surface_id */, - cc::CompositorFrameAck); + uint32_t /* compositor_frame_sink_id */, + cc::ReturnedResourceArray /* resources */); IPC_MESSAGE_ROUTED1(SyncCompositorMsg_SetScroll, gfx::ScrollOffset); // ----------------------------------------------------------------------------- // Messages sent from the renderer to the browser. -IPC_MESSAGE_ROUTED0(SyncCompositorHostMsg_OutputSurfaceCreated); +IPC_MESSAGE_ROUTED0(SyncCompositorHostMsg_CompositorFrameSinkCreated); IPC_MESSAGE_ROUTED1(SyncCompositorHostMsg_UpdateState, content::SyncCompositorCommonRendererParams) + +IPC_MESSAGE_ROUTED2(SyncCompositorHostMsg_ReturnFrame, + uint32_t /* compositor_frame_sink_id */, + cc::CompositorFrame); diff --git a/chromium/content/common/associated_interface_provider_impl.cc b/chromium/content/common/associated_interface_provider_impl.cc new file mode 100644 index 00000000000..c42ff3f15e0 --- /dev/null +++ b/chromium/content/common/associated_interface_provider_impl.cc @@ -0,0 +1,28 @@ +// 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/common/associated_interface_provider_impl.h" + +namespace content { + +AssociatedInterfaceProviderImpl::AssociatedInterfaceProviderImpl( + mojom::AssociatedInterfaceProviderAssociatedPtr proxy) + : proxy_(std::move(proxy)) { +} + +AssociatedInterfaceProviderImpl::~AssociatedInterfaceProviderImpl() {} + +void AssociatedInterfaceProviderImpl::GetInterface( + const std::string& name, + mojo::ScopedInterfaceEndpointHandle handle) { + mojom::AssociatedInterfaceAssociatedRequest request; + request.Bind(std::move(handle)); + return proxy_->GetAssociatedInterface(name, std::move(request)); +} + +mojo::AssociatedGroup* AssociatedInterfaceProviderImpl::GetAssociatedGroup() { + return proxy_.associated_group(); +} + +} // namespace content diff --git a/chromium/content/common/associated_interface_provider_impl.h b/chromium/content/common/associated_interface_provider_impl.h new file mode 100644 index 00000000000..af01ce55427 --- /dev/null +++ b/chromium/content/common/associated_interface_provider_impl.h @@ -0,0 +1,33 @@ +// 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/common/associated_interface_provider.h" + +#include <stdint.h> + +#include "base/macros.h" +#include "content/common/associated_interfaces.mojom.h" +#include "mojo/public/cpp/bindings/associated_group.h" + +namespace content { + +class AssociatedInterfaceProviderImpl : public AssociatedInterfaceProvider { + public: + // Binds this to a remote mojom::AssociatedInterfaceProvider. + explicit AssociatedInterfaceProviderImpl( + mojom::AssociatedInterfaceProviderAssociatedPtr proxy); + ~AssociatedInterfaceProviderImpl() override; + + // AssociatedInterfaceProvider: + void GetInterface(const std::string& name, + mojo::ScopedInterfaceEndpointHandle handle) override; + mojo::AssociatedGroup* GetAssociatedGroup() override; + + private: + mojom::AssociatedInterfaceProviderAssociatedPtr proxy_; + + DISALLOW_COPY_AND_ASSIGN(AssociatedInterfaceProviderImpl); +}; + +} // namespace content diff --git a/chromium/content/common/associated_interface_registry_impl.cc b/chromium/content/common/associated_interface_registry_impl.cc new file mode 100644 index 00000000000..67b5b0e4e54 --- /dev/null +++ b/chromium/content/common/associated_interface_registry_impl.cc @@ -0,0 +1,38 @@ +// 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/common/associated_interface_registry_impl.h" + +#include <utility> + +#include "base/logging.h" + +namespace content { + +AssociatedInterfaceRegistryImpl::AssociatedInterfaceRegistryImpl() {} + +AssociatedInterfaceRegistryImpl::~AssociatedInterfaceRegistryImpl() {} + +void AssociatedInterfaceRegistryImpl::BindRequest( + const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle handle) { + auto it = interfaces_.find(interface_name); + if (it == interfaces_.end()) + return; + it->second.Run(std::move(handle)); +} + +void AssociatedInterfaceRegistryImpl::AddInterface(const std::string& name, + const Binder& binder) { + auto result = interfaces_.insert(std::make_pair(name, binder)); + DCHECK(result.second); +} + +void AssociatedInterfaceRegistryImpl::RemoveInterface(const std::string& name) { + auto it = interfaces_.find(name); + DCHECK(it != interfaces_.end()); + interfaces_.erase(it); +} + +} // namespace content diff --git a/chromium/content/common/associated_interface_registry_impl.h b/chromium/content/common/associated_interface_registry_impl.h new file mode 100644 index 00000000000..1f624a2f8ef --- /dev/null +++ b/chromium/content/common/associated_interface_registry_impl.h @@ -0,0 +1,37 @@ +// 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_COMMON_ASSOCIATED_INTERFACE_REGISTRY_IMPL_H_ +#define CONTENT_COMMON_ASSOCIATED_INTERFACE_REGISTRY_IMPL_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "content/public/common/associated_interface_registry.h" +#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" + +namespace content { + +class AssociatedInterfaceRegistryImpl : public AssociatedInterfaceRegistry { + public: + AssociatedInterfaceRegistryImpl(); + ~AssociatedInterfaceRegistryImpl() override; + + void BindRequest(const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle handle); + + // AssociatedInterfaceRegistry: + void AddInterface(const std::string& name, const Binder& binder) override; + void RemoveInterface(const std::string& name) override; + + private: + std::map<std::string, Binder> interfaces_; + + DISALLOW_COPY_AND_ASSIGN(AssociatedInterfaceRegistryImpl); +}; + +} // namespace content + +#endif // CONTENT_COMMON_ASSOCIATED_INTERFACE_REGISTRY_IMPL_H_ diff --git a/chromium/content/common/associated_interfaces.mojom b/chromium/content/common/associated_interfaces.mojom new file mode 100644 index 00000000000..f6b871a6756 --- /dev/null +++ b/chromium/content/common/associated_interfaces.mojom @@ -0,0 +1,21 @@ +// 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. + +module content.mojom; + +// A generic, nominal interface to support transitional Channel-associated +// interfaces at or above the content layer. +interface AssociatedInterface {}; + +// Analogous to the generic InterfaceProvider interface, but for content +// AssociatedInterfaces. +interface AssociatedInterfaceProvider { + GetAssociatedInterface(string name, associated AssociatedInterface& request); +}; + +// Implemented by anything which manages one or more routes, to map a routing +// ID to an AssociatedInterfaceProvider. +interface RouteProvider { + GetRoute(int32 routing_id, associated AssociatedInterfaceProvider& request); +}; diff --git a/chromium/content/common/bluetooth/OWNERS b/chromium/content/common/bluetooth/OWNERS new file mode 100644 index 00000000000..e1158f6c802 --- /dev/null +++ b/chromium/content/common/bluetooth/OWNERS @@ -0,0 +1,8 @@ +jyasskin@chromium.org +ortuno@chromium.org +scheib@chromium.org + +# Changes to IPC serialization require a security review to avoid introducing +# new sandbox escapes. +per-file *_struct_traits*.*=set noparent +per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS diff --git a/chromium/content/common/bluetooth/PRESUBMIT.py b/chromium/content/common/bluetooth/PRESUBMIT.py new file mode 100644 index 00000000000..5af5a089498 --- /dev/null +++ b/chromium/content/common/bluetooth/PRESUBMIT.py @@ -0,0 +1,14 @@ +# 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. + +"""Presubmit script. + +See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts +for more details about the presubmit API built into depot_tools. +""" + +def CheckChangeOnUpload(input_api, output_api): + results = [] + results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api) + return results diff --git a/chromium/content/common/bluetooth/typemaps.gni b/chromium/content/common/bluetooth/typemaps.gni new file mode 100644 index 00000000000..552e6cfe128 --- /dev/null +++ b/chromium/content/common/bluetooth/typemaps.gni @@ -0,0 +1,5 @@ +# 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. + +typemaps = [ "//content/common/bluetooth/web_bluetooth_device_id.typemap" ] diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id.cc b/chromium/content/common/bluetooth/web_bluetooth_device_id.cc new file mode 100644 index 00000000000..823ed0fd979 --- /dev/null +++ b/chromium/content/common/bluetooth/web_bluetooth_device_id.cc @@ -0,0 +1,87 @@ +// 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/common/bluetooth/web_bluetooth_device_id.h" + +#include "base/base64.h" +#include "base/strings/string_util.h" +#include "crypto/random.h" + +namespace content { + +namespace { + +enum { kDeviceIdLength = 16 /* 128 bits */ }; + +} // namespace + +WebBluetoothDeviceId::WebBluetoothDeviceId() {} + +WebBluetoothDeviceId::WebBluetoothDeviceId(std::string device_id) + : device_id_(std::move(device_id)) { + CHECK(IsValid(device_id_)); +} + +WebBluetoothDeviceId::~WebBluetoothDeviceId() {} + +const std::string& WebBluetoothDeviceId::str() const { + CHECK(IsValid(device_id_)); + return device_id_; +} + +// static +WebBluetoothDeviceId WebBluetoothDeviceId::Create() { + std::string bytes( + kDeviceIdLength + 1 /* to avoid bytes being reallocated by WriteInto */, + '\0'); + + crypto::RandBytes(base::WriteInto(&bytes /* str */, + kDeviceIdLength + 1 /* length_with_null */), + kDeviceIdLength); + + base::Base64Encode(bytes, &bytes); + + return WebBluetoothDeviceId(std::move(bytes)); +} + +// static +bool WebBluetoothDeviceId::IsValid(const std::string& device_id) { + std::string decoded; + if (!base::Base64Decode(device_id, &decoded)) { + return false; + } + + if (decoded.size() != kDeviceIdLength) { + return false; + } + + // When base64-encoding a 128bit string, only the two MSB are used for + // the 3rd-to-last character. Because of this, the 3rd-to-last character + // can only be one of this four characters. + if (!(device_id[device_id.size() - 3] == 'A' || + device_id[device_id.size() - 3] == 'Q' || + device_id[device_id.size() - 3] == 'g' || + device_id[device_id.size() - 3] == 'w')) { + return false; + } + + return true; +} + +bool WebBluetoothDeviceId::operator==( + const WebBluetoothDeviceId& device_id) const { + return str() == device_id.str(); +} + +bool WebBluetoothDeviceId::operator!=( + const WebBluetoothDeviceId& device_id) const { + return !(*this == device_id); +} + +std::ostream& operator<<(std::ostream& out, + const WebBluetoothDeviceId& device_id) { + return out << device_id.str(); +} + +} // namespace content diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id.h b/chromium/content/common/bluetooth/web_bluetooth_device_id.h new file mode 100644 index 00000000000..2de12a022df --- /dev/null +++ b/chromium/content/common/bluetooth/web_bluetooth_device_id.h @@ -0,0 +1,58 @@ +// 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_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ +#define CONTENT_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ + +#include <string> + +#include "content/common/content_export.h" + +namespace content { + +// Used to uniquely identify a Bluetooth Device for an Origin. +// A WebBluetoothDeviceId is generated by base64-encoding a 128bit +// string. +class CONTENT_EXPORT WebBluetoothDeviceId { + public: + // Default constructor that creates an invalid id. We implement it so that + // instances of this class in a container, e.g. std::unordered_map, can be + // accessed through the [] operator. Trying to call any function of the + // resulting object will DCHECK-fail. + WebBluetoothDeviceId(); + + // DCHECKS that |device_id| is valid. + explicit WebBluetoothDeviceId(std::string device_id); + ~WebBluetoothDeviceId(); + + // Returns the string that represents this WebBluetoothDeviceId. + const std::string& str() const; + + // The returned WebBluetoothDeviceId is generated by creating a random 128bit + // string and base64-encoding it. + static WebBluetoothDeviceId Create(); + + // Returns true if base64-decoding |device_id| results in a 128bit string. + static bool IsValid(const std::string& device_id); + + bool operator==(const WebBluetoothDeviceId& device_id) const; + bool operator!=(const WebBluetoothDeviceId& device_id) const; + + private: + std::string device_id_; +}; + +// This is required by gtest to print a readable output on test failures. +CONTENT_EXPORT std::ostream& operator<<(std::ostream& out, + const WebBluetoothDeviceId& device_id); + +struct WebBluetoothDeviceIdHash { + size_t operator()(const WebBluetoothDeviceId& device_id) const { + return std::hash<std::string>()(device_id.str()); + } +}; + +} // namespace content + +#endif // CONTENT_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap b/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap new file mode 100644 index 00000000000..7f07b52b538 --- /dev/null +++ b/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap @@ -0,0 +1,11 @@ +# 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. + +mojom = + "//third_party/WebKit/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" ] +type_mappings = + [ "blink.mojom.WebBluetoothDeviceId=content::WebBluetoothDeviceId" ] 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 new file mode 100644 index 00000000000..08b9f11edbf --- /dev/null +++ b/chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h @@ -0,0 +1,39 @@ +// 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_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ +#define CONTENT_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ + +#include <string> + +#include "content/common/bluetooth/web_bluetooth_device_id.h" +#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h" + +namespace mojo { + +template <> +struct StructTraits<blink::mojom::WebBluetoothDeviceIdDataView, + content::WebBluetoothDeviceId> { + static const std::string& device_id( + const content::WebBluetoothDeviceId& device_id) { + return device_id.str(); + } + + static bool Read(blink::mojom::WebBluetoothDeviceIdDataView input, + content::WebBluetoothDeviceId* output) { + std::string result; + + if (!input.ReadDeviceId(&result)) + return false; + if (!content::WebBluetoothDeviceId::IsValid(result)) + return false; + + *output = content::WebBluetoothDeviceId(std::move(result)); + return true; + } +}; + +} // namespace mojo + +#endif // CONTENT_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id_unittest.cc b/chromium/content/common/bluetooth/web_bluetooth_device_id_unittest.cc new file mode 100644 index 00000000000..44f7daafc40 --- /dev/null +++ b/chromium/content/common/bluetooth/web_bluetooth_device_id_unittest.cc @@ -0,0 +1,81 @@ +// 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/common/bluetooth/web_bluetooth_device_id.h" + +#include "base/base64.h" +#include "base/strings/string_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +using content::WebBluetoothDeviceId; + +namespace { + +const char kValidDeviceId1[] = "123456789012345678901A=="; +const char kValidDeviceId2[] = "AbCdEfGhIjKlMnOpQrS+/Q=="; +const char kInvalidLongDeviceId[] = "12345678901234567890123="; +const char kInvalidShortDeviceId[] = "12345678901234567890"; +const char kInvalidCharacterDeviceId[] = "123456789012345678901*=="; +// A base64 string should have a length of a multiple of 4. +const char kInvalidLengthDeviceId[] = "123456789012345678901"; + +} // namespace + +TEST(WebBluetoothDeviceIdTest, DefaultConstructor) { + WebBluetoothDeviceId default_id1; + WebBluetoothDeviceId default_id2; + WebBluetoothDeviceId valid_id(kValidDeviceId1); + + ASSERT_DEATH_IF_SUPPORTED(default_id1.str(), ""); + ASSERT_DEATH_IF_SUPPORTED(default_id2.str(), ""); + ASSERT_TRUE(WebBluetoothDeviceId::IsValid(valid_id.str())); + + EXPECT_DEATH_IF_SUPPORTED([&]() { return default_id1 == default_id2; }(), ""); + EXPECT_DEATH_IF_SUPPORTED([&]() { return default_id1 != default_id2; }(), ""); + + EXPECT_DEATH_IF_SUPPORTED([&]() { return default_id1 == valid_id; }(), ""); + EXPECT_DEATH_IF_SUPPORTED([&]() { return valid_id == default_id1; }(), ""); + + EXPECT_DEATH_IF_SUPPORTED([&]() { return default_id1 != valid_id; }(), ""); + EXPECT_DEATH_IF_SUPPORTED([&]() { return valid_id != default_id1; }(), ""); +} + +TEST(WebBluetoothDeviceIdTest, StrConstructor) { + WebBluetoothDeviceId valid1(kValidDeviceId1); + WebBluetoothDeviceId valid2(kValidDeviceId2); + + EXPECT_TRUE(valid1 == valid1); + EXPECT_TRUE(valid2 == valid2); + + EXPECT_TRUE(valid1 != valid2); + + EXPECT_DEATH_IF_SUPPORTED(WebBluetoothDeviceId(""), ""); + EXPECT_DEATH_IF_SUPPORTED( + [&]() { return WebBluetoothDeviceId(kInvalidLongDeviceId); }(), ""); + EXPECT_DEATH_IF_SUPPORTED( + [&]() { return WebBluetoothDeviceId(kInvalidShortDeviceId); }(), ""); + EXPECT_DEATH_IF_SUPPORTED( + [&]() { return WebBluetoothDeviceId(kInvalidCharacterDeviceId); }(), ""); + EXPECT_DEATH_IF_SUPPORTED( + [&]() { return WebBluetoothDeviceId(kInvalidLengthDeviceId); }(), ""); +} + +TEST(WebBluetoothDeviceIdTest, IsValid_Valid) { + EXPECT_TRUE(WebBluetoothDeviceId::IsValid(kValidDeviceId1)); + EXPECT_TRUE(WebBluetoothDeviceId::IsValid(kValidDeviceId2)); +} + +TEST(WebBluetoothDeviceIdTest, IsValid_Invalid) { + EXPECT_FALSE(WebBluetoothDeviceId::IsValid("")); + EXPECT_FALSE(WebBluetoothDeviceId::IsValid(kInvalidLongDeviceId)); + EXPECT_FALSE(WebBluetoothDeviceId::IsValid(kInvalidShortDeviceId)); + EXPECT_FALSE(WebBluetoothDeviceId::IsValid(kInvalidCharacterDeviceId)); + EXPECT_FALSE(WebBluetoothDeviceId::IsValid(kInvalidLengthDeviceId)); +} + +TEST(WebBluetoothDeviceIdTest, Create) { + // Tests that Create generates a valid Device Id. + EXPECT_TRUE( + WebBluetoothDeviceId::IsValid(WebBluetoothDeviceId::Create().str())); +} diff --git a/chromium/content/common/browser_plugin/browser_plugin_messages.h b/chromium/content/common/browser_plugin/browser_plugin_messages.h index 4161dafa06c..ada01838990 100644 --- a/chromium/content/common/browser_plugin/browser_plugin_messages.h +++ b/chromium/content/common/browser_plugin/browser_plugin_messages.h @@ -73,10 +73,15 @@ IPC_MESSAGE_CONTROL5( int /* selection_end */) // This message is sent from BrowserPlugin to BrowserPluginGuest to notify that -// confirming the current composition is requested. -IPC_MESSAGE_CONTROL3(BrowserPluginHostMsg_ImeConfirmComposition, +// deleting the current composition and inserting specified text is requested. +IPC_MESSAGE_CONTROL3(BrowserPluginHostMsg_ImeCommitText, int /* browser_plugin_instance_id */, std::string /* text */, + int /* relative_cursor_pos */) + +// This message is sent from BrowserPlugin to BrowserPluginGuest to notify that +// inserting the current composition is requested. +IPC_MESSAGE_CONTROL1(BrowserPluginHostMsg_ImeFinishComposingText, bool /* keep selection */) // Deletes the current selection plus the specified number of characters before diff --git a/chromium/content/common/cache_storage/cache_storage_types.h b/chromium/content/common/cache_storage/cache_storage_types.h index 22e91c0636a..fb04e5b72cf 100644 --- a/chromium/content/common/cache_storage/cache_storage_types.h +++ b/chromium/content/common/cache_storage/cache_storage_types.h @@ -8,7 +8,7 @@ #include <map> #include <string> -#include "base/strings/string16.h" +#include "base/strings/nullable_string16.h" #include "content/common/content_export.h" #include "content/common/service_worker/service_worker_types.h" @@ -21,10 +21,10 @@ namespace content { struct CONTENT_EXPORT CacheStorageCacheQueryParams { CacheStorageCacheQueryParams(); - bool ignore_search; - bool ignore_method; - bool ignore_vary; - base::string16 cache_name; + bool ignore_search = false; + bool ignore_method = false; + bool ignore_vary = false; + base::NullableString16 cache_name; }; // The type of a single batch operation in the Cache API. @@ -56,7 +56,8 @@ enum CacheStorageError { CACHE_STORAGE_ERROR_NOT_FOUND, CACHE_STORAGE_ERROR_QUOTA_EXCEEDED, CACHE_STORAGE_ERROR_CACHE_NAME_NOT_FOUND, - CACHE_STORAGE_ERROR_LAST = CACHE_STORAGE_ERROR_CACHE_NAME_NOT_FOUND + CACHE_STORAGE_ERROR_QUERY_TOO_LARGE, + CACHE_STORAGE_ERROR_LAST = CACHE_STORAGE_ERROR_QUERY_TOO_LARGE }; } // namespace content diff --git a/chromium/content/common/child_memory_coordinator.mojom b/chromium/content/common/child_memory_coordinator.mojom new file mode 100644 index 00000000000..0a20b7fbd3f --- /dev/null +++ b/chromium/content/common/child_memory_coordinator.mojom @@ -0,0 +1,23 @@ +// 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. + +module content.mojom; + +// See base/memory/memory_coordinator_client.h for the definitions of these +// states. +enum MemoryState { + UNKNOWN = -1, + NORMAL = 0, + THROTTLED = 1, + SUSPENDED = 2, +}; + +// ChildMemoryCoordinator lives in a child process and receives memory events +// dispatched by the central memory coordinator which lives in the browser +// process. +interface ChildMemoryCoordinator { + // Called when the central memory coodinator changes the state for child + // processes. + OnStateChange(MemoryState state); +}; diff --git a/chromium/content/common/child_process_host_impl.cc b/chromium/content/common/child_process_host_impl.cc index 1dc475da372..23c339f2aa1 100644 --- a/chromium/content/common/child_process_host_impl.cc +++ b/chromium/content/common/child_process_host_impl.cc @@ -12,7 +12,7 @@ #include "base/hash.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/numerics/safe_math.h" #include "base/path_service.h" #include "base/process/process_metrics.h" @@ -20,6 +20,7 @@ #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" +#include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "content/common/child_process_messages.h" #include "content/public/common/child_process_host_delegate.h" @@ -28,11 +29,13 @@ #include "gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h" #include "ipc/attachment_broker.h" #include "ipc/attachment_broker_privileged.h" +#include "ipc/ipc.mojom.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_channel_mojo.h" #include "ipc/ipc_logging.h" #include "ipc/message_filter.h" #include "mojo/edk/embedder/embedder.h" +#include "services/shell/public/cpp/interface_provider.h" #if defined(OS_LINUX) #include "base/linux_util.h" @@ -128,6 +131,10 @@ void ChildProcessHostImpl::AddFilter(IPC::MessageFilter* filter) { filter->OnFilterAdded(channel_.get()); } +shell::InterfaceProvider* ChildProcessHostImpl::GetRemoteInterfaces() { + return delegate_->GetRemoteInterfaces(); +} + void ChildProcessHostImpl::ForceShutdown() { Send(new ChildProcessMsg_Shutdown()); } @@ -146,20 +153,31 @@ std::string ChildProcessHostImpl::CreateChannelMojo( return channel_id_; } -std::string ChildProcessHostImpl::CreateChannel() { +void ChildProcessHostImpl::CreateChannelMojo() { + // TODO(rockot): Remove |channel_id_| once this is the only code path by which + // the Channel is created. For now it serves to at least mutually exclude + // different CreateChannel* calls. DCHECK(channel_id_.empty()); - channel_id_ = IPC::Channel::GenerateVerifiedChannelID(std::string()); - channel_ = IPC::Channel::CreateServer(channel_id_, this); - if (!channel_ || !InitChannel()) - return std::string(); + channel_id_ = "ChannelMojo"; - return channel_id_; + shell::InterfaceProvider* remote_interfaces = GetRemoteInterfaces(); + DCHECK(remote_interfaces); + + IPC::mojom::ChannelBootstrapPtr bootstrap; + remote_interfaces->GetInterface(&bootstrap); + channel_ = IPC::ChannelMojo::Create(bootstrap.PassInterface().PassHandle(), + IPC::Channel::MODE_SERVER, this); + DCHECK(channel_); + + bool initialized = InitChannel(); + DCHECK(initialized); } bool ChildProcessHostImpl::InitChannel() { #if USE_ATTACHMENT_BROKER + DCHECK(base::MessageLoopForIO::IsCurrent()); IPC::AttachmentBroker::GetGlobal()->RegisterCommunicationChannel( - channel_.get(), base::MessageLoopForIO::current()->task_runner()); + channel_.get(), base::ThreadTaskRunnerHandle::Get()); #endif if (!channel_->Connect()) { #if USE_ATTACHMENT_BROKER diff --git a/chromium/content/common/child_process_host_impl.h b/chromium/content/common/child_process_host_impl.h index 686a7737319..f1734f2075e 100644 --- a/chromium/content/common/child_process_host_impl.h +++ b/chromium/content/common/child_process_host_impl.h @@ -78,10 +78,11 @@ class CONTENT_EXPORT ChildProcessHostImpl : public ChildProcessHost, // ChildProcessHost implementation bool Send(IPC::Message* message) override; void ForceShutdown() override; - std::string CreateChannel() override; std::string CreateChannelMojo(const std::string& child_token) override; + void CreateChannelMojo() override; bool IsChannelOpening() override; void AddFilter(IPC::MessageFilter* filter) override; + shell::InterfaceProvider* GetRemoteInterfaces() override; #if defined(OS_POSIX) base::ScopedFD TakeClientFileDescriptor() override; #endif diff --git a/chromium/content/common/child_process_messages.h b/chromium/content/common/child_process_messages.h index 34d3e6444c9..a3c48897e71 100644 --- a/chromium/content/common/child_process_messages.h +++ b/chromium/content/common/child_process_messages.h @@ -17,7 +17,6 @@ #include "cc/resources/shared_bitmap_manager.h" #include "content/common/content_export.h" #include "content/common/content_param_traits_macros.h" -#include "content/common/gpu_process_launch_causes.h" #include "content/common/host_discardable_shared_memory_manager.h" #include "gpu/command_buffer/common/sync_token.h" #include "gpu/ipc/common/gpu_param_traits_macros.h" @@ -28,8 +27,9 @@ #include "ui/gfx/ipc/gfx_param_traits.h" #include "ui/gfx/ipc/skia/gfx_skia_param_traits.h" -IPC_ENUM_TRAITS_MAX_VALUE(content::CauseForGpuLaunch, - content::CAUSE_FOR_GPU_LAUNCH_MAX_ENUM - 1) +#if defined(OS_LINUX) +#include "base/threading/platform_thread.h" +#endif IPC_ENUM_TRAITS_MAX_VALUE(tracked_objects::ThreadData::Status, tracked_objects::ThreadData::STATUS_LAST) @@ -70,6 +70,11 @@ IPC_STRUCT_TRAITS_BEGIN(tracked_objects::ProcessDataSnapshot) IPC_STRUCT_TRAITS_MEMBER(process_id) IPC_STRUCT_TRAITS_END() +#if defined(OS_LINUX) +IPC_ENUM_TRAITS_MAX_VALUE(base::ThreadPriority, + base::ThreadPriority::REALTIME_AUDIO) +#endif + #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT @@ -127,8 +132,7 @@ IPC_MESSAGE_CONTROL0(ChildProcessMsg_PurgeAndSuspend) // A renderer sends this when it wants to create a connection to the GPU // process. The browser will create the GPU process if necessary, and will // return a handle to the channel via a GpuChannelEstablished message. -IPC_SYNC_MESSAGE_CONTROL1_3(ChildProcessHostMsg_EstablishGpuChannel, - content::CauseForGpuLaunch, +IPC_SYNC_MESSAGE_CONTROL0_3(ChildProcessHostMsg_EstablishGpuChannel, int /* client id */, IPC::ChannelHandle /* handle to channel */, gpu::GPUInfo /* stats about GPU process*/) @@ -216,3 +220,10 @@ IPC_SYNC_MESSAGE_CONTROL2_1( // memory. IPC_MESSAGE_CONTROL1(ChildProcessHostMsg_DeletedDiscardableSharedMemory, content::DiscardableSharedMemoryId) + +#if defined(OS_LINUX) +// Asks the browser to change the priority of thread. +IPC_MESSAGE_CONTROL2(ChildProcessHostMsg_SetThreadPriority, + base::PlatformThreadId, + base::ThreadPriority) +#endif diff --git a/chromium/content/common/common.gni b/chromium/content/common/common.gni deleted file mode 100644 index 8a794fa104f..00000000000 --- a/chromium/content/common/common.gni +++ /dev/null @@ -1,13 +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. - -# This file defines the content common gypi values. This file is read once and -# cached, which is a performance optimization that allows us to share the -# results of parsing the .gypi file between the public and private BUILD.gn -# files. It also saves us from duplicating this exec_script call. -content_common_gypi_values = - exec_script("//build/gypi_to_gn.py", - [ rebase_path("../content_common.gypi") ], - "scope", - [ "../content_common.gypi" ]) diff --git a/chromium/content/common/content_message_generator.h b/chromium/content/common/content_message_generator.h index c9ed8ceda99..de63cc92f8c 100644 --- a/chromium/content/common/content_message_generator.h +++ b/chromium/content/common/content_message_generator.h @@ -13,9 +13,6 @@ #include "content/common/cache_storage/cache_storage_messages.h" #include "content/common/clipboard_messages.h" #include "content/common/database_messages.h" -#include "content/common/device_sensors/device_light_messages.h" -#include "content/common/device_sensors/device_motion_messages.h" -#include "content/common/device_sensors/device_orientation_messages.h" #include "content/common/devtools_messages.h" #include "content/common/dom_storage/dom_storage_messages.h" #include "content/common/drag_messages.h" @@ -39,7 +36,6 @@ #include "content/common/media/midi_messages.h" #include "content/common/media/peer_connection_tracker_messages.h" #include "content/common/media/video_capture_messages.h" -#include "content/common/media/webrtc_identity_messages.h" #include "content/common/memory_messages.h" #include "content/common/message_port_messages.h" #include "content/common/page_messages.h" @@ -56,7 +52,6 @@ #include "content/common/text_input_client_messages.h" #include "content/common/utility_messages.h" #include "content/common/view_messages.h" -#include "content/common/websocket_messages.h" #include "content/common/worker_messages.h" #if defined(ENABLE_WEBRTC) @@ -67,7 +62,6 @@ #include "content/common/android/sync_compositor_messages.h" #include "content/common/gin_java_bridge_messages.h" #include "content/common/media/media_player_messages_android.h" -#include "content/common/media/media_session_messages_android.h" #include "content/common/media/surface_view_manager_messages_android.h" #endif // defined(OS_ANDROID) diff --git a/chromium/content/common/content_param_traits.cc b/chromium/content/common/content_param_traits.cc index 7b441c3f1c0..6cff525a3d3 100644 --- a/chromium/content/common/content_param_traits.cc +++ b/chromium/content/common/content_param_traits.cc @@ -7,8 +7,8 @@ #include <stddef.h> #include "base/strings/string_number_conversions.h" -#include "content/common/input/web_input_event_traits.h" #include "net/base/ip_endpoint.h" +#include "ui/events/blink/web_input_event_traits.h" namespace IPC { @@ -42,7 +42,7 @@ bool ParamTraits<WebInputEventPointer>::Read(const base::Pickle* m, return false; } const size_t expected_size_for_type = - content::WebInputEventTraits::GetSize(event->type); + ui::WebInputEventTraits::GetSize(event->type); if (data_length != static_cast<int>(expected_size_for_type)) { NOTREACHED(); return false; diff --git a/chromium/content/common/content_switches_internal.cc b/chromium/content/common/content_switches_internal.cc index d4716f96def..c0f0cc6550f 100644 --- a/chromium/content/common/content_switches_internal.cc +++ b/chromium/content/common/content_switches_internal.cc @@ -27,7 +27,7 @@ const base::Feature kUseZoomForDsfEnabledByDefault { #endif bool IsUseZoomForDSFEnabledByDefault() { -#if defined(OS_CHROMEOS) +#if defined(OS_CHROMEOS) || defined(OS_LINUX) return true; #elif defined(OS_WIN) return base::FeatureList::IsEnabled(kUseZoomForDsfEnabledByDefault); diff --git a/chromium/content/common/cross_site_document_classifier.cc b/chromium/content/common/cross_site_document_classifier.cc index 85778cbea7a..cc87c08d4b0 100644 --- a/chromium/content/common/cross_site_document_classifier.cc +++ b/chromium/content/common/cross_site_document_classifier.cc @@ -8,7 +8,7 @@ #include "base/lazy_instance.h" #include "base/logging.h" #include "base/macros.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "content/public/common/content_switches.h" #include "content/public/common/resource_response_info.h" diff --git a/chromium/content/common/device_sensors/device_light_hardware_buffer.h b/chromium/content/common/device_sensors/device_light_hardware_buffer.h index dcd0f1b57f7..1664af0cdb5 100644 --- a/chromium/content/common/device_sensors/device_light_hardware_buffer.h +++ b/chromium/content/common/device_sensors/device_light_hardware_buffer.h @@ -6,11 +6,12 @@ #define CONTENT_COMMON_DEVICE_SENSORS_DEVICE_LIGHT_HARDWARE_BUFFER_H_ #include "content/common/device_sensors/device_light_data.h" -#include "content/common/shared_memory_seqlock_buffer.h" +#include "device/base/synchronization/shared_memory_seqlock_buffer.h" namespace content { -typedef SharedMemorySeqLockBuffer<DeviceLightData> DeviceLightHardwareBuffer; +typedef device::SharedMemorySeqLockBuffer<DeviceLightData> + DeviceLightHardwareBuffer; } // namespace content diff --git a/chromium/content/common/device_sensors/device_light_messages.h b/chromium/content/common/device_sensors/device_light_messages.h deleted file mode 100644 index 4fad255468b..00000000000 --- a/chromium/content/common/device_sensors/device_light_messages.h +++ /dev/null @@ -1,26 +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. - -// IPC messages for device light. -// Multiply-included message file, hence no include guard. - -#include "base/memory/shared_memory.h" -#include "ipc/ipc_message_macros.h" -#include "ipc/ipc_param_traits.h" -#include "ipc/ipc_platform_file.h" - -#define IPC_MESSAGE_START DeviceLightMsgStart - -// Asks the browser process to activate Device Light sensors if necessary. -IPC_MESSAGE_CONTROL0(DeviceLightHostMsg_StartPolling) - -// The browser process asynchronously returns the shared memory handle that -// will hold the data from the hardware sensors. -IPC_MESSAGE_CONTROL1(DeviceLightMsg_DidStartPolling, - base::SharedMemoryHandle /* handle */) - -// Notifies the browser process that the renderer process is not using the -// Device Light data anymore. The number of Starts should match the number -// of Stops. -IPC_MESSAGE_CONTROL0(DeviceLightHostMsg_StopPolling) diff --git a/chromium/content/common/device_sensors/device_motion_hardware_buffer.h b/chromium/content/common/device_sensors/device_motion_hardware_buffer.h index d387cdac3d6..ea49290ba86 100644 --- a/chromium/content/common/device_sensors/device_motion_hardware_buffer.h +++ b/chromium/content/common/device_sensors/device_motion_hardware_buffer.h @@ -5,12 +5,12 @@ #ifndef CONTENT_COMMON_DEVICE_SENSORS_DEVICE_MOTION_HARDWARE_BUFFER_H_ #define CONTENT_COMMON_DEVICE_SENSORS_DEVICE_MOTION_HARDWARE_BUFFER_H_ -#include "content/common/shared_memory_seqlock_buffer.h" +#include "device/base/synchronization/shared_memory_seqlock_buffer.h" #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionData.h" namespace content { -typedef SharedMemorySeqLockBuffer<blink::WebDeviceMotionData> +typedef device::SharedMemorySeqLockBuffer<blink::WebDeviceMotionData> DeviceMotionHardwareBuffer; } // namespace content diff --git a/chromium/content/common/device_sensors/device_motion_messages.h b/chromium/content/common/device_sensors/device_motion_messages.h deleted file mode 100644 index 4b17d1024dc..00000000000 --- a/chromium/content/common/device_sensors/device_motion_messages.h +++ /dev/null @@ -1,28 +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. - -// IPC messages for device motion. -// Multiply-included message file, hence no include guard. - -#include "base/memory/shared_memory.h" -#include "ipc/ipc_message_macros.h" -#include "ipc/ipc_param_traits.h" -#include "ipc/ipc_platform_file.h" - -#define IPC_MESSAGE_START DeviceMotionMsgStart - -// Asks the browser process to activate Device Motion sensors if necessary. -IPC_MESSAGE_CONTROL0(DeviceMotionHostMsg_StartPolling) - -// The browser process asynchronously returns the shared memory handle that will -// hold the data from the hardware sensors. -// See device_motion_hardware_buffer.h for a description of how -// synchronization is handled. -IPC_MESSAGE_CONTROL1(DeviceMotionMsg_DidStartPolling, - base::SharedMemoryHandle /* handle */) - -// Notifies the browser process that the renderer process is not using the -// Device Motion data anymore. The number of Starts should match the number -// of Stops. -IPC_MESSAGE_CONTROL0(DeviceMotionHostMsg_StopPolling) diff --git a/chromium/content/common/device_sensors/device_orientation_hardware_buffer.h b/chromium/content/common/device_sensors/device_orientation_hardware_buffer.h index c7a0ae87981..66c6fdc4411 100644 --- a/chromium/content/common/device_sensors/device_orientation_hardware_buffer.h +++ b/chromium/content/common/device_sensors/device_orientation_hardware_buffer.h @@ -5,12 +5,12 @@ #ifndef CONTENT_COMMON_DEVICE_SENSORS_DEVICE_ORIENTATION_HARDWARE_BUFFER_H_ #define CONTENT_COMMON_DEVICE_SENSORS_DEVICE_ORIENTATION_HARDWARE_BUFFER_H_ -#include "content/common/shared_memory_seqlock_buffer.h" +#include "device/base/synchronization/shared_memory_seqlock_buffer.h" #include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationData.h" namespace content { -typedef SharedMemorySeqLockBuffer<blink::WebDeviceOrientationData> +typedef device::SharedMemorySeqLockBuffer<blink::WebDeviceOrientationData> DeviceOrientationHardwareBuffer; } // namespace content diff --git a/chromium/content/common/device_sensors/device_orientation_messages.h b/chromium/content/common/device_sensors/device_orientation_messages.h deleted file mode 100644 index 7c7b475bdfb..00000000000 --- a/chromium/content/common/device_sensors/device_orientation_messages.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// IPC messages for device orientation. -// Multiply-included message file, hence no include guard. - -#include "base/memory/shared_memory.h" -#include "ipc/ipc_message_macros.h" - -#define IPC_MESSAGE_START DeviceOrientationMsgStart - -// Asks the browser process to activate Device Orientation sensors if necessary. -IPC_MESSAGE_CONTROL0(DeviceOrientationHostMsg_StartPolling) - -// The browser process asynchronously returns the shared memory handle that will -// hold the data from the hardware sensors. -// See device_orientation_hardware_buffer.h for a description of how -// synchronization is handled. -IPC_MESSAGE_CONTROL1(DeviceOrientationMsg_DidStartPolling, - base::SharedMemoryHandle /* handle */) - -// Notifies the browser process that the renderer process is not using the -// Device Orientation data anymore. The number of Starts should match the -// number of Stops. -IPC_MESSAGE_CONTROL0(DeviceOrientationHostMsg_StopPolling) - -// Same as above except the messages relate to Absolute Device Orientation, -// where orientation is provided w.r.t. a predefined coordinate frame. -IPC_MESSAGE_CONTROL0(DeviceOrientationAbsoluteHostMsg_StartPolling) -IPC_MESSAGE_CONTROL1(DeviceOrientationAbsoluteMsg_DidStartPolling, - base::SharedMemoryHandle /* handle */) -IPC_MESSAGE_CONTROL0(DeviceOrientationAbsoluteHostMsg_StopPolling) diff --git a/chromium/content/common/devtools_messages.h b/chromium/content/common/devtools_messages.h index 7a888762df8..8bafd0a53cf 100644 --- a/chromium/content/common/devtools_messages.h +++ b/chromium/content/common/devtools_messages.h @@ -100,7 +100,8 @@ IPC_MESSAGE_ROUTED4(DevToolsAgentMsg_DispatchOnInspectorBackend, std::string /* message */) // Inspect element with the given coordinates. -IPC_MESSAGE_ROUTED2(DevToolsAgentMsg_InspectElement, +IPC_MESSAGE_ROUTED3(DevToolsAgentMsg_InspectElement, + int /* session_id */, int /* x */, int /* y */) diff --git a/chromium/content/common/font_cache_dispatcher_win.cc b/chromium/content/common/font_cache_dispatcher_win.cc index d0d053e7340..09da8f76cdb 100644 --- a/chromium/content/common/font_cache_dispatcher_win.cc +++ b/chromium/content/common/font_cache_dispatcher_win.cc @@ -151,8 +151,8 @@ bool FontCacheDispatcher::Send(IPC::Message* message) { FontCacheDispatcher::~FontCacheDispatcher() { } -void FontCacheDispatcher::OnFilterAdded(IPC::Sender* sender) { - sender_ = sender; +void FontCacheDispatcher::OnFilterAdded(IPC::Channel* channel) { + sender_ = channel; } bool FontCacheDispatcher::OnMessageReceived(const IPC::Message& message) { diff --git a/chromium/content/common/font_cache_dispatcher_win.h b/chromium/content/common/font_cache_dispatcher_win.h index dbdcb4f462b..e5d5ca0799b 100644 --- a/chromium/content/common/font_cache_dispatcher_win.h +++ b/chromium/content/common/font_cache_dispatcher_win.h @@ -28,7 +28,7 @@ class FontCacheDispatcher : public IPC::MessageFilter, public IPC::Sender { ~FontCacheDispatcher() override; // IPC::MessageFilter implementation: - void OnFilterAdded(IPC::Sender* sender) override; + void OnFilterAdded(IPC::Channel* channel) override; bool OnMessageReceived(const IPC::Message& message) override; void OnChannelClosing() override; diff --git a/chromium/content/common/font_config_ipc_linux.h b/chromium/content/common/font_config_ipc_linux.h index 258c2002083..0fc85ec5ef4 100644 --- a/chromium/content/common/font_config_ipc_linux.h +++ b/chromium/content/common/font_config_ipc_linux.h @@ -39,8 +39,6 @@ class FontConfigIPC : public SkFontConfigInterface { SkString* outFamilyName, SkFontStyle* outStyle) override; - // Returns a new SkTypeface instance or a ref'ed one from the cache. The - // caller should adopt the pointer. sk_sp<SkTypeface> makeTypeface(const FontIdentity& identity) override WARN_UNUSED_RESULT; diff --git a/chromium/content/common/font_list_fontconfig.cc b/chromium/content/common/font_list_fontconfig.cc new file mode 100644 index 00000000000..7f52829845d --- /dev/null +++ b/chromium/content/common/font_list_fontconfig.cc @@ -0,0 +1,72 @@ +// 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/common/font_list.h" + +#include <memory> +#include <set> +#include <string> +#include <utility> + +#include <fontconfig/fontconfig.h> + +#include "base/values.h" + +namespace content { + +std::unique_ptr<FcPattern, decltype(&FcPatternDestroy)> CreateFormatPattern( + const char* format) { + std::unique_ptr<FcPattern, decltype(&FcPatternDestroy)> pattern( + FcPatternCreate(), FcPatternDestroy); + FcPatternAddBool(pattern.get(), FC_SCALABLE, FcTrue); + FcPatternAddString(pattern.get(), FC_FONTFORMAT, + reinterpret_cast<const FcChar8*>(format)); + return pattern; +} + +std::unique_ptr<base::ListValue> GetFontList_SlowBlocking() { + std::unique_ptr<base::ListValue> font_list(new base::ListValue); + + std::unique_ptr<FcObjectSet, decltype(&FcObjectSetDestroy)> object_set( + FcObjectSetBuild(FC_FAMILY, NULL), FcObjectSetDestroy); + + std::set<std::string> sorted_families; + + // See https://www.freetype.org/freetype2/docs/reference/ft2-font_formats.html + // for the list of possible formats. + const char* allowed_formats[] = { "TrueType", "CFF" }; + for (size_t i = 0; i < arraysize(allowed_formats); ++i) { + auto format_pattern = CreateFormatPattern(allowed_formats[i]); + std::unique_ptr<FcFontSet, decltype(&FcFontSetDestroy)> fontset( + FcFontList(0, format_pattern.get(), object_set.get()), + FcFontSetDestroy); + for (int j = 0; j < fontset->nfont; ++j) { + char* family_string; + FcPatternGetString(fontset->fonts[j], FC_FAMILY, 0, + reinterpret_cast<FcChar8**>(&family_string)); + sorted_families.insert(family_string); + } + } + + // For backwards compatibility with the older pango implementation, add the + // three Fontconfig aliases that pango added. Our linux default settings for + // fixed-width was "Monospace". If we remove that, this entry is not found in + // the list anymore, see also: + // https://git.gnome.org/browse/pango/tree/pango/pangofc-fontmap.c?h=1.40.1#n1351 + sorted_families.insert("Monospace"); + sorted_families.insert("Sans"); + sorted_families.insert("Serif"); + + for (const auto& family : sorted_families) { + std::unique_ptr<base::ListValue> font_item(new base::ListValue()); + font_item->AppendString(family); + font_item->AppendString(family); // localized name. + // TODO(yusukes): Support localized family names. + font_list->Append(std::move(font_item)); + } + + return font_list; +} + +} // namespace content diff --git a/chromium/content/common/font_list_ozone.cc b/chromium/content/common/font_list_ozone.cc deleted file mode 100644 index 73df7284312..00000000000 --- a/chromium/content/common/font_list_ozone.cc +++ /dev/null @@ -1,15 +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/common/font_list.h" - -#include "base/values.h" - -namespace content { - -std::unique_ptr<base::ListValue> GetFontList_SlowBlocking() { - return std::unique_ptr<base::ListValue>(new base::ListValue); -} - -} // namespace content diff --git a/chromium/content/common/font_list_pango.cc b/chromium/content/common/font_list_pango.cc deleted file mode 100644 index f7d82fc5a22..00000000000 --- a/chromium/content/common/font_list_pango.cc +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/font_list.h" - -#include <pango/pango.h> -#include <pango/pangocairo.h> - -#include <set> -#include <string> -#include <utility> - -#include "base/values.h" - -namespace content { - -std::unique_ptr<base::ListValue> GetFontList_SlowBlocking() { - std::unique_ptr<base::ListValue> font_list(new base::ListValue); - - PangoFontMap* font_map = ::pango_cairo_font_map_get_default(); - PangoFontFamily** families = NULL; - int num_families = 0; - ::pango_font_map_list_families(font_map, &families, &num_families); - - std::set<std::string> sorted_families; - for (int i = 0; i < num_families; i++) { - sorted_families.insert(::pango_font_family_get_name(families[i])); - } - g_free(families); - - for (std::set<std::string>::const_iterator iter = sorted_families.begin(); - iter != sorted_families.end(); ++iter) { - std::unique_ptr<base::ListValue> font_item(new base::ListValue()); - font_item->AppendString(*iter); - font_item->AppendString(*iter); // localized name. - // TODO(yusukes): Support localized family names. - font_list->Append(std::move(font_item)); - } - - return font_list; -} - -} // namespace content diff --git a/chromium/content/common/frame_messages.h b/chromium/content/common/frame_messages.h index 2e53dc5d387..2329016c258 100644 --- a/chromium/content/common/frame_messages.h +++ b/chromium/content/common/frame_messages.h @@ -20,6 +20,7 @@ #include "content/common/content_param_traits.h" #include "content/common/content_security_policy_header.h" #include "content/common/frame_message_enums.h" +#include "content/common/frame_owner_properties.h" #include "content/common/frame_replication_state.h" #include "content/common/navigation_gesture.h" #include "content/common/navigation_params.h" @@ -93,6 +94,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(blink::WebContextMenuData::InputFieldType, IPC_ENUM_TRAITS_MAX_VALUE(blink::WebFocusType, blink::WebFocusTypeLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebFrameOwnerProperties::ScrollingMode, blink::WebFrameOwnerProperties::ScrollingMode::Last) +IPC_ENUM_TRAITS_MAX_VALUE(blink::WebPermissionType, + blink::WebPermissionTypeLast) IPC_ENUM_TRAITS_MAX_VALUE(content::StopFindAction, content::STOP_FIND_ACTION_LAST) IPC_ENUM_TRAITS(blink::WebSandboxFlags) // Bitmask. @@ -109,6 +112,7 @@ IPC_STRUCT_TRAITS_BEGIN(blink::WebFindOptions) IPC_STRUCT_TRAITS_MEMBER(forward) IPC_STRUCT_TRAITS_MEMBER(matchCase) IPC_STRUCT_TRAITS_MEMBER(findNext) + IPC_STRUCT_TRAITS_MEMBER(force) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::ColorSuggestion) @@ -143,7 +147,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::ContextMenuParams) IPC_STRUCT_TRAITS_MEMBER(writing_direction_left_to_right) IPC_STRUCT_TRAITS_MEMBER(writing_direction_right_to_left) IPC_STRUCT_TRAITS_MEMBER(edit_flags) - IPC_STRUCT_TRAITS_MEMBER(security_info) IPC_STRUCT_TRAITS_MEMBER(frame_charset) IPC_STRUCT_TRAITS_MEMBER(referrer_policy) IPC_STRUCT_TRAITS_MEMBER(custom_context) @@ -163,11 +166,13 @@ IPC_STRUCT_TRAITS_BEGIN(content::CustomContextMenuContext) IPC_STRUCT_TRAITS_MEMBER(link_followed) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(blink::WebFrameOwnerProperties) - IPC_STRUCT_TRAITS_MEMBER(scrollingMode) - IPC_STRUCT_TRAITS_MEMBER(marginWidth) - IPC_STRUCT_TRAITS_MEMBER(marginHeight) - IPC_STRUCT_TRAITS_MEMBER(allowFullscreen) +IPC_STRUCT_TRAITS_BEGIN(content::FrameOwnerProperties) + IPC_STRUCT_TRAITS_MEMBER(scrolling_mode) + IPC_STRUCT_TRAITS_MEMBER(margin_width) + IPC_STRUCT_TRAITS_MEMBER(margin_height) + IPC_STRUCT_TRAITS_MEMBER(allow_fullscreen) + IPC_STRUCT_TRAITS_MEMBER(required_csp) + IPC_STRUCT_TRAITS_MEMBER(delegated_permissions) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::TransitionElement) @@ -231,10 +236,6 @@ IPC_STRUCT_BEGIN_WITH_PARENT(FrameHostMsg_DidCommitProvisionalLoad_Params, // Whether this commit should replace the current entry. IPC_STRUCT_MEMBER(bool, should_replace_current_entry) - // Information regarding the security of the connection (empty if the - // connection was not secure). - IPC_STRUCT_MEMBER(std::string, security_info) - // The gesture that initiated this navigation. IPC_STRUCT_MEMBER(content::NavigationGesture, gesture) @@ -256,10 +257,6 @@ IPC_STRUCT_BEGIN_WITH_PARENT(FrameHostMsg_DidCommitProvisionalLoad_Params, // so that we can set the appropriate page type. IPC_STRUCT_MEMBER(bool, url_is_unreachable) - // True if the connection was proxied. In this case, socket_address - // will represent the address of the proxy, rather than the remote host. - IPC_STRUCT_MEMBER(bool, was_fetched_via_proxy) - // Serialized history item state to store in the navigation entry. IPC_STRUCT_MEMBER(content::PageState, page_state) @@ -357,22 +354,28 @@ IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::StartNavigationParams) IPC_STRUCT_TRAITS_MEMBER(extra_headers) -#if defined(OS_ANDROID) - IPC_STRUCT_TRAITS_MEMBER(has_user_gesture) -#endif IPC_STRUCT_TRAITS_MEMBER(transferred_request_child_id) IPC_STRUCT_TRAITS_MEMBER(transferred_request_request_id) IPC_STRUCT_TRAITS_END() +IPC_STRUCT_TRAITS_BEGIN(content::NavigationTiming) + IPC_STRUCT_TRAITS_MEMBER(redirect_start) + IPC_STRUCT_TRAITS_MEMBER(redirect_end) + IPC_STRUCT_TRAITS_MEMBER(fetch_start) +IPC_STRUCT_TRAITS_END() + IPC_STRUCT_TRAITS_BEGIN(content::RequestNavigationParams) IPC_STRUCT_TRAITS_MEMBER(is_overriding_user_agent) IPC_STRUCT_TRAITS_MEMBER(redirects) + IPC_STRUCT_TRAITS_MEMBER(redirect_response) IPC_STRUCT_TRAITS_MEMBER(can_load_local_resources) IPC_STRUCT_TRAITS_MEMBER(request_time) IPC_STRUCT_TRAITS_MEMBER(page_state) IPC_STRUCT_TRAITS_MEMBER(page_id) IPC_STRUCT_TRAITS_MEMBER(nav_entry_id) IPC_STRUCT_TRAITS_MEMBER(is_same_document_history_load) + IPC_STRUCT_TRAITS_MEMBER(is_history_navigation_in_new_child) + IPC_STRUCT_TRAITS_MEMBER(subframe_unique_names) IPC_STRUCT_TRAITS_MEMBER(has_committed_real_load) IPC_STRUCT_TRAITS_MEMBER(intended_as_new_entry) IPC_STRUCT_TRAITS_MEMBER(pending_history_list_offset) @@ -381,6 +384,9 @@ IPC_STRUCT_TRAITS_BEGIN(content::RequestNavigationParams) IPC_STRUCT_TRAITS_MEMBER(is_view_source) IPC_STRUCT_TRAITS_MEMBER(should_clear_history_list) IPC_STRUCT_TRAITS_MEMBER(should_create_service_worker) + IPC_STRUCT_TRAITS_MEMBER(navigation_timing) + IPC_STRUCT_TRAITS_MEMBER(service_worker_provider_id) + IPC_STRUCT_TRAITS_MEMBER(has_user_gesture) #if defined(OS_ANDROID) IPC_STRUCT_TRAITS_MEMBER(data_url_as_string) #endif @@ -397,58 +403,9 @@ IPC_STRUCT_TRAITS_BEGIN(content::FrameReplicationState) IPC_STRUCT_TRAITS_MEMBER(has_potentially_trustworthy_unique_origin) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_BEGIN(FrameMsg_NewFrame_WidgetParams) - // Gives the routing ID for the RenderWidget that will be attached to the - // new RenderFrame. If the RenderFrame does not need a RenderWidget, this - // is MSG_ROUTING_NONE and the other parameters are not read. - IPC_STRUCT_MEMBER(int, routing_id) - - // Tells the new RenderWidget whether it is initially hidden. - IPC_STRUCT_MEMBER(bool, hidden) -IPC_STRUCT_END() - -IPC_STRUCT_BEGIN(FrameMsg_NewFrame_Params) - // Specifies the routing ID of the new RenderFrame object. - IPC_STRUCT_MEMBER(int, routing_id) - - // If a valid |proxy_routing_id| is provided, the new frame will be - // configured to replace the proxy on commit. - IPC_STRUCT_MEMBER(int, proxy_routing_id) - - // Specifies the new frame's opener. The opener will be null if this is - // MSG_ROUTING_NONE. - IPC_STRUCT_MEMBER(int, opener_routing_id) - - // The new frame should be created as a child of the object - // identified by |parent_routing_id| or as top level if that is - // MSG_ROUTING_NONE. - IPC_STRUCT_MEMBER(int, parent_routing_id) - - // Identifies the previous sibling of the new frame, so that the new frame is - // inserted into the correct place in the frame tree. If this is - // MSG_ROUTING_NONE, the frame will be created as the leftmost child of its - // parent frame, in front of any other children. - IPC_STRUCT_MEMBER(int, previous_sibling_routing_id) - - // When the new frame has a parent, |replication_state| holds the new frame's - // properties replicated from the process rendering the parent frame, such as - // the new frame's sandbox flags. - IPC_STRUCT_MEMBER(content::FrameReplicationState, replication_state) - - // When the new frame has a parent, |frame_owner_properties| holds the - // properties of the HTMLFrameOwnerElement from the parent process. - // Note that unlike FrameReplicationState, this is not replicated for remote - // frames. - IPC_STRUCT_MEMBER(blink::WebFrameOwnerProperties, frame_owner_properties) - - // Specifies properties for a new RenderWidget that will be attached to the - // new RenderFrame (if one is needed). - IPC_STRUCT_MEMBER(FrameMsg_NewFrame_WidgetParams, widget_params) -IPC_STRUCT_END() - -// Parameters included with an OpenURL request. |frame_unique_name| is only -// specified if |is_history_navigation_in_new_child| is true, for the case that -// the browser process should look for an existing history item for the frame. +// Parameters included with an OpenURL request. +// |is_history_navigation_in_new_child| is true in the case that the browser +// process should look for an existing history item for the frame. IPC_STRUCT_BEGIN(FrameHostMsg_OpenURL_Params) IPC_STRUCT_MEMBER(GURL, url) IPC_STRUCT_MEMBER(bool, uses_post) @@ -459,7 +416,6 @@ IPC_STRUCT_BEGIN(FrameHostMsg_OpenURL_Params) IPC_STRUCT_MEMBER(bool, should_replace_current_entry) IPC_STRUCT_MEMBER(bool, user_gesture) IPC_STRUCT_MEMBER(bool, is_history_navigation_in_new_child) - IPC_STRUCT_MEMBER(std::string, frame_unique_name) IPC_STRUCT_END() IPC_STRUCT_BEGIN(FrameMsg_TextTrackSettings_Params) @@ -550,7 +506,7 @@ IPC_STRUCT_BEGIN(FrameHostMsg_CreateChildFrame_Params) IPC_STRUCT_MEMBER(std::string, frame_name) IPC_STRUCT_MEMBER(std::string, frame_unique_name) IPC_STRUCT_MEMBER(blink::WebSandboxFlags, sandbox_flags) - IPC_STRUCT_MEMBER(blink::WebFrameOwnerProperties, frame_owner_properties) + IPC_STRUCT_MEMBER(content::FrameOwnerProperties, frame_owner_properties) IPC_STRUCT_END() IPC_STRUCT_TRAITS_BEGIN(content::ContentSecurityPolicyHeader) @@ -653,26 +609,9 @@ IPC_MESSAGE_ROUTED1(FrameMsg_UpdateOpener, int /* opener_routing_id */) // commit, activation and frame swap of the current DOM tree in blink. IPC_MESSAGE_ROUTED1(FrameMsg_VisualStateRequest, uint64_t /* id */) -// Instructs the renderer to create a new RenderFrame object. -IPC_MESSAGE_CONTROL1(FrameMsg_NewFrame, FrameMsg_NewFrame_Params /* params */) - // Instructs the renderer to delete the RenderFrame. IPC_MESSAGE_ROUTED0(FrameMsg_Delete) -// Instructs the renderer to create a new RenderFrameProxy object with -// |routing_id|. |render_view_routing_id| identifies the -// RenderView to be associated with this proxy. The new proxy's opener should -// be set to the object identified by |opener_routing_id|, or to null if that -// is MSG_ROUTING_NONE. The new proxy should be created as a child of the -// object identified by |parent_routing_id| or as top level if that is -// MSG_ROUTING_NONE. -IPC_MESSAGE_CONTROL5(FrameMsg_NewFrameProxy, - int /* routing_id */, - int /* render_view_routing_id */, - int /* opener_routing_id */, - int /* parent_routing_id */, - content::FrameReplicationState /* replication_state */) - // Tells the renderer to perform the specified navigation, interrupting any // existing navigation. IPC_MESSAGE_ROUTED3(FrameMsg_Navigate, @@ -703,10 +642,6 @@ IPC_MESSAGE_ROUTED0(FrameMsg_DidStartLoading) // RenderFrame has completed loading. IPC_MESSAGE_ROUTED0(FrameMsg_DidStopLoading) -// Request for the renderer to insert CSS into the frame. -IPC_MESSAGE_ROUTED1(FrameMsg_CSSInsertRequest, - std::string /* css */) - // Add message to the frame console. IPC_MESSAGE_ROUTED2(FrameMsg_AddMessageToConsole, content::ConsoleMessageLevel /* level */, @@ -826,6 +761,10 @@ IPC_MESSAGE_ROUTED2(FrameMsg_DidUpdateOrigin, // support cross-process focused frame changes. IPC_MESSAGE_ROUTED0(FrameMsg_SetFocusedFrame) +// Notifies this frame or proxy that it is no longer focused. This is used when +// a frame in the embedder that the guest cannot see (<webview>) gains focus. +IPC_MESSAGE_ROUTED0(FrameMsg_ClearFocusedFrame) + // Sent to a frame proxy when its real frame is preparing to enter fullscreen // in another process. Actually entering fullscreen will be done separately as // part of ViewMsg_Resize, once the browser process has resized the tab for @@ -891,7 +830,7 @@ IPC_MESSAGE_ROUTED4(FrameMsg_CommitNavigation, content::ResourceResponseHead, /* response */ GURL, /* stream_url */ content::CommonNavigationParams, /* common_params */ - content::RequestNavigationParams) /* request_params */ + content::RequestNavigationParams /* request_params */) // PlzNavigate // Tells the renderer that a navigation failed with the error code |error_code| @@ -920,7 +859,7 @@ IPC_MESSAGE_ROUTED2(FrameMsg_GetSerializedHtmlWithLocalLinks, IPC_MESSAGE_ROUTED1(FrameMsg_SerializeAsMHTML, FrameMsg_SerializeAsMHTML_Params) IPC_MESSAGE_ROUTED1(FrameMsg_SetFrameOwnerProperties, - blink::WebFrameOwnerProperties /* frame_owner_properties */) + content::FrameOwnerProperties /* frame_owner_properties */) // Request to continue running the sequential focus navigation algorithm in // this frame. |source_routing_id| identifies the frame that issued this @@ -1083,6 +1022,11 @@ IPC_MESSAGE_ROUTED1(FrameHostMsg_DidChangeLoadProgress, // Requests that the given URL be opened in the specified manner. IPC_MESSAGE_ROUTED1(FrameHostMsg_OpenURL, FrameHostMsg_OpenURL_Params) +// If a cross-process navigation was started for the initial history load in +// this subframe, this tries to cancel it to allow a client redirect to happen +// instead. +IPC_MESSAGE_ROUTED0(FrameHostMsg_CancelInitialHistoryLoad) + // Notifies the browser that a frame finished loading. IPC_MESSAGE_ROUTED1(FrameHostMsg_DidFinishLoad, GURL /* validated_url */) @@ -1135,7 +1079,7 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_DidChangeSandboxFlags, // of this frame. IPC_MESSAGE_ROUTED2(FrameHostMsg_DidChangeFrameOwnerProperties, int32_t /* subframe_routing_id */, - blink::WebFrameOwnerProperties /* frame_owner_properties */) + content::FrameOwnerProperties /* frame_owner_properties */) // Changes the title for the page in the UI when the page is navigated or the // title changes. Sent for top-level frames. @@ -1156,22 +1100,6 @@ IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdateEncoding, IPC_MESSAGE_ROUTED1(FrameHostMsg_DomOperationResponse, std::string /* json_string */) -// Used to set a cookie. The cookie is set asynchronously, but will be -// available to a subsequent FrameHostMsg_GetCookies request. -IPC_MESSAGE_CONTROL4(FrameHostMsg_SetCookie, - int /* render_frame_id */, - GURL /* url */, - GURL /* first_party_for_cookies */, - std::string /* cookie */) - -// Used to get cookies for the given URL. This may block waiting for a -// previous SetCookie message to be processed. -IPC_SYNC_MESSAGE_CONTROL3_1(FrameHostMsg_GetCookies, - int /* render_frame_id */, - GURL /* url */, - GURL /* first_party_for_cookies */, - std::string /* cookies */) - // Used to check if cookies are enabled for the given URL. This may block // waiting for a previous SetCookie message to be processed. IPC_SYNC_MESSAGE_CONTROL3_1(FrameHostMsg_CookiesEnabled, @@ -1191,11 +1119,13 @@ IPC_SYNC_MESSAGE_CONTROL3_1(FrameHostMsg_Are3DAPIsBlocked, #if defined(ENABLE_PLUGINS) // Notification sent from a renderer to the browser that a Pepper plugin // instance is created in the DOM. -IPC_MESSAGE_ROUTED0(FrameHostMsg_PepperInstanceCreated) +IPC_MESSAGE_ROUTED1(FrameHostMsg_PepperInstanceCreated, + int32_t /* pp_instance */) // Notification sent from a renderer to the browser that a Pepper plugin // instance is deleted from the DOM. -IPC_MESSAGE_ROUTED0(FrameHostMsg_PepperInstanceDeleted) +IPC_MESSAGE_ROUTED1(FrameHostMsg_PepperInstanceDeleted, + int32_t /* pp_instance */) // Sent to the browser when the renderer detects it is blocked on a pepper // plugin message for too long. This is also sent when it becomes unhung @@ -1215,10 +1145,22 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_PluginCrashed, base::FilePath /* plugin_path */, base::ProcessId /* plugin_pid */) -// Used to get the list of plugins -IPC_SYNC_MESSAGE_CONTROL1_1(FrameHostMsg_GetPlugins, - bool /* refresh*/, - std::vector<content::WebPluginInfo> /* plugins */) +// Notification sent from a renderer to the browser that a Pepper plugin +// instance has started playback. +IPC_MESSAGE_ROUTED1(FrameHostMsg_PepperStartsPlayback, + int32_t /* pp_instance */) + +// Notification sent from a renderer to the browser that a Pepper plugin +// instance has stopped playback. +IPC_MESSAGE_ROUTED1(FrameHostMsg_PepperStopsPlayback, + int32_t /* pp_instance */) + +// Used to get the list of plugins. |main_frame_origin| is used to handle +// exceptions for plugin content settings. +IPC_SYNC_MESSAGE_CONTROL2_1(FrameHostMsg_GetPlugins, + bool /* refresh*/, + url::Origin /* main_frame_origin */, + std::vector<content::WebPluginInfo> /* plugins */) // Return information about a plugin for the given URL and MIME // type. If there is no matching plugin, |found| is false. @@ -1227,7 +1169,7 @@ IPC_SYNC_MESSAGE_CONTROL1_1(FrameHostMsg_GetPlugins, IPC_SYNC_MESSAGE_CONTROL4_3(FrameHostMsg_GetPluginInfo, int /* render_frame_id */, GURL /* url */, - GURL /* page_url */, + url::Origin /* main_frame_origin */, std::string /* mime_type */, bool /* found */, content::WebPluginInfo /* plugin info */, @@ -1352,11 +1294,6 @@ IPC_MESSAGE_ROUTED1(FrameHostMsg_VisibilityChanged, bool /* visible */) // user right clicked. IPC_MESSAGE_ROUTED1(FrameHostMsg_ContextMenu, content::ContextMenuParams) -// Initial drawing parameters for a child frame that has been swapped out to -// another process. -IPC_MESSAGE_ROUTED1(FrameHostMsg_InitializeChildFrame, - float /* scale_factor */) - // Response for FrameMsg_JavaScriptExecuteRequest, sent when a reply was // requested. The ID is the parameter supplied to // FrameMsg_JavaScriptExecuteRequest. The result has the value returned by the @@ -1426,9 +1363,8 @@ IPC_MESSAGE_ROUTED3(FrameHostMsg_UnregisterProtocolHandler, // The security info is non empty if the resource was originally loaded over // a secure connection. // Note: May only be sent once per URL per frame per committed load. -IPC_MESSAGE_ROUTED5(FrameHostMsg_DidLoadResourceFromMemoryCache, +IPC_MESSAGE_ROUTED4(FrameHostMsg_DidLoadResourceFromMemoryCache, GURL /* url */, - std::string /* security info */, std::string /* http method */, std::string /* mime type */, content::ResourceType /* resource type */) @@ -1466,15 +1402,13 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_DidRunInsecureContent, // Sent when the renderer displays content that was loaded with // certificate errors. -IPC_MESSAGE_ROUTED2(FrameHostMsg_DidDisplayContentWithCertificateErrors, - GURL /* resource url */, - std::string /* serialized security info */) +IPC_MESSAGE_ROUTED1(FrameHostMsg_DidDisplayContentWithCertificateErrors, + GURL /* resource url */) // Sent when the renderer runs content that was loaded with certificate // errors. -IPC_MESSAGE_ROUTED2(FrameHostMsg_DidRunContentWithCertificateErrors, - GURL /* resource url */, - std::string /* serialized security info */) +IPC_MESSAGE_ROUTED1(FrameHostMsg_DidRunContentWithCertificateErrors, + GURL /* resource url */) // Response to FrameMsg_GetSavableResourceLinks. IPC_MESSAGE_ROUTED3(FrameHostMsg_SavableResourceLinksResponse, @@ -1493,11 +1427,12 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_SerializedHtmlWithLocalLinksResponse, bool /* end of data? */) // Response to FrameMsg_SerializeAsMHTML. -IPC_MESSAGE_ROUTED3( +IPC_MESSAGE_ROUTED4( FrameHostMsg_SerializeAsMHTMLResponse, int /* job_id (used to match responses to requests) */, bool /* true if success, false if error */, - std::set<std::string> /* digests of uris of serialized resources */) + std::set<std::string> /* digests of uris of serialized resources */, + base::TimeDelta /* how much time of the main render thread was used */) // Sent when the renderer updates hint for importance of a tab. IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdatePageImportanceSignals, diff --git a/chromium/content/common/frame_owner_properties.cc b/chromium/content/common/frame_owner_properties.cc new file mode 100644 index 00000000000..e84de423701 --- /dev/null +++ b/chromium/content/common/frame_owner_properties.cc @@ -0,0 +1,56 @@ +// 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/common/frame_owner_properties.h" + +namespace content { + +FrameOwnerProperties::FrameOwnerProperties() + : scrolling_mode(blink::WebFrameOwnerProperties::ScrollingMode::Auto), + margin_width(-1), + margin_height(-1), + allow_fullscreen(false) {} + +FrameOwnerProperties::FrameOwnerProperties(const FrameOwnerProperties& other) = + default; + +FrameOwnerProperties::FrameOwnerProperties( + const blink::WebFrameOwnerProperties& web_frame_owner_properties) + : scrolling_mode(web_frame_owner_properties.scrollingMode), + margin_width(web_frame_owner_properties.marginWidth), + margin_height(web_frame_owner_properties.marginHeight), + allow_fullscreen(web_frame_owner_properties.allowFullscreen), + required_csp(web_frame_owner_properties.requiredCsp.utf8()), + delegated_permissions( + web_frame_owner_properties.delegatedPermissions.begin(), + web_frame_owner_properties.delegatedPermissions.end()) {} + +FrameOwnerProperties::~FrameOwnerProperties() {} + +blink::WebFrameOwnerProperties FrameOwnerProperties::ToWebFrameOwnerProperties() + const { + blink::WebFrameOwnerProperties result; + + result.scrollingMode = scrolling_mode; + result.marginWidth = margin_width; + result.marginHeight = margin_height; + result.allowFullscreen = allow_fullscreen; + result.requiredCsp = blink::WebString::fromUTF8(required_csp); + result.delegatedPermissions = + blink::WebVector<blink::WebPermissionType>(delegated_permissions); + + return result; +} + +bool FrameOwnerProperties::operator==(const FrameOwnerProperties& other) const { + return scrolling_mode == other.scrolling_mode && + margin_width == other.margin_width && + margin_height == other.margin_height && + allow_fullscreen == other.allow_fullscreen && + required_csp == other.required_csp && + std::equal(delegated_permissions.begin(), delegated_permissions.end(), + other.delegated_permissions.begin()); +} + +} // namespace content diff --git a/chromium/content/common/frame_owner_properties.h b/chromium/content/common/frame_owner_properties.h new file mode 100644 index 00000000000..157c82334dd --- /dev/null +++ b/chromium/content/common/frame_owner_properties.h @@ -0,0 +1,50 @@ +// 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_COMMON_FRAME_OWNER_PROPERTIES_H_ +#define CONTENT_COMMON_FRAME_OWNER_PROPERTIES_H_ + +#include <vector> + +#include "content/common/content_export.h" +#include "third_party/WebKit/public/platform/modules/permissions/WebPermissionType.h" +#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h" + +namespace content { + +// Used for IPC transport of WebFrameOwnerProperties. WebFrameOwnerProperties +// can't be used directly as it contains a WebVector which doesn't have +// ParamTraits defined. +struct CONTENT_EXPORT FrameOwnerProperties { + FrameOwnerProperties(); + FrameOwnerProperties(const FrameOwnerProperties& other); + explicit FrameOwnerProperties( + const blink::WebFrameOwnerProperties& web_frame_owner_properties); + ~FrameOwnerProperties(); + + blink::WebFrameOwnerProperties ToWebFrameOwnerProperties() const; + + bool operator==(const FrameOwnerProperties& other) const; + bool operator!=(const FrameOwnerProperties& other) const { + return !(*this == other); + } + + blink::WebFrameOwnerProperties::ScrollingMode scrolling_mode; + int margin_width; + int margin_height; + bool allow_fullscreen; + + // An experimental attribute to be used by a parent frame to enforce CSP on a + // subframe. This is different from replicated CSP headers kept in + // FrameReplicationState that keep track of CSP headers currently in effect + // for a frame. See https://crbug.com/647588 and + // https://www.w3.org/TR/csp-embedded-enforcement/#required-csp + std::string required_csp; + + std::vector<blink::WebPermissionType> delegated_permissions; +}; + +} // namespace content + +#endif // CONTENT_COMMON_FRAME_OWNER_PROPERTIES_H_ diff --git a/chromium/content/common/gamepad_hardware_buffer.h b/chromium/content/common/gamepad_hardware_buffer.h index 4d3182525a3..5098cb1b014 100644 --- a/chromium/content/common/gamepad_hardware_buffer.h +++ b/chromium/content/common/gamepad_hardware_buffer.h @@ -5,7 +5,7 @@ #ifndef CONTENT_COMMON_GAMEPAD_HARDWARE_BUFFER_H_ #define CONTENT_COMMON_GAMEPAD_HARDWARE_BUFFER_H_ -#include "content/common/one_writer_seqlock.h" +#include "device/base/synchronization/one_writer_seqlock.h" #include "third_party/WebKit/public/platform/WebGamepads.h" namespace content { @@ -25,7 +25,7 @@ contention is detected by using the associated SeqLock. struct GamepadHardwareBuffer { // FIXME: Use the generic SharedMemorySeqLockBuffer<blink::WebGamepads>. - OneWriterSeqLock sequence; + device::OneWriterSeqLock sequence; blink::WebGamepads buffer; }; diff --git a/chromium/content/common/gpu/OWNERS b/chromium/content/common/gpu/OWNERS index 0ea6b105a42..158c900c592 100644 --- a/chromium/content/common/gpu/OWNERS +++ b/chromium/content/common/gpu/OWNERS @@ -2,9 +2,6 @@ ccameron@chromium.org jbauman@chromium.org kbr@chromium.org -# GPU memory buffer implementations. -per-file *gpu_memory_buffer*=reveman@chromium.org - # GPU memory manager. per-file *gpu_memory_manager*=ccameron@chromium.org diff --git a/chromium/content/common/gpu/client/command_buffer_metrics.cc b/chromium/content/common/gpu/client/command_buffer_metrics.cc index bc70c88bbdd..223e49f4f86 100644 --- a/chromium/content/common/gpu/client/command_buffer_metrics.cc +++ b/chromium/content/common/gpu/client/command_buffer_metrics.cc @@ -4,7 +4,7 @@ #include "content/common/gpu/client/command_buffer_metrics.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" namespace content { namespace command_buffer_metrics { @@ -117,6 +117,12 @@ void RecordContextLost(ContextType type, UMA_HISTOGRAM_ENUMERATION("GPU.ContextLost.Media", reason, CONTEXT_LOST_REASON_MAX_ENUM); break; + case BLIMP_RENDER_COMPOSITOR_CONTEXT: + UMA_HISTOGRAM_ENUMERATION("GPU.ContextLost.BlimpRenderCompositor", reason, + CONTEXT_LOST_REASON_MAX_ENUM); + case BLIMP_RENDER_WORKER_CONTEXT: + UMA_HISTOGRAM_ENUMERATION("GPU.ContextLost.BlimpRenderWorker", reason, + CONTEXT_LOST_REASON_MAX_ENUM); case CONTEXT_TYPE_UNKNOWN: UMA_HISTOGRAM_ENUMERATION("GPU.ContextLost.Unknown", reason, CONTEXT_LOST_REASON_MAX_ENUM); @@ -150,6 +156,10 @@ std::string ContextTypeToString(ContextType type) { return "Offscreen-For-WebGL"; case MEDIA_CONTEXT: return "Media"; + case BLIMP_RENDER_COMPOSITOR_CONTEXT: + return "BlimpRenderCompositor"; + case BLIMP_RENDER_WORKER_CONTEXT: + return "BlimpRenderWorker"; default: NOTREACHED(); return "unknown"; diff --git a/chromium/content/common/gpu/client/command_buffer_metrics.h b/chromium/content/common/gpu/client/command_buffer_metrics.h index 67f609cabcc..f508fa7d8ae 100644 --- a/chromium/content/common/gpu/client/command_buffer_metrics.h +++ b/chromium/content/common/gpu/client/command_buffer_metrics.h @@ -24,6 +24,8 @@ enum ContextType { OFFSCREEN_CONTEXT_FOR_WEBGL, CONTEXT_TYPE_UNKNOWN, MEDIA_CONTEXT, + BLIMP_RENDER_COMPOSITOR_CONTEXT, + BLIMP_RENDER_WORKER_CONTEXT, OFFSCREEN_CONTEXT_FOR_TESTING = CONTEXT_TYPE_UNKNOWN, }; diff --git a/chromium/content/common/gpu/client/context_provider_command_buffer.cc b/chromium/content/common/gpu/client/context_provider_command_buffer.cc index a1411c8ab01..e717ac253b3 100644 --- a/chromium/content/common/gpu/client/context_provider_command_buffer.cc +++ b/chromium/content/common/gpu/client/context_provider_command_buffer.cc @@ -15,6 +15,7 @@ #include "base/command_line.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" +#include "cc/output/context_cache_controller.h" #include "cc/output/managed_memory_policy.h" #include "content/common/gpu/client/command_buffer_metrics.h" #include "gpu/command_buffer/client/gles2_cmd_helper.h" @@ -149,8 +150,6 @@ bool ContextProviderCommandBuffer::BindToCurrentThread() { DCHECK_EQ(!!shared_command_buffer, !!share_group); } - DCHECK(attributes_.buffer_preserved); - // This command buffer is a client-side proxy to the command buffer in the // GPU process. scoped_refptr<base::SingleThreadTaskRunner> task_runner = @@ -159,7 +158,7 @@ bool ContextProviderCommandBuffer::BindToCurrentThread() { task_runner = base::ThreadTaskRunnerHandle::Get(); command_buffer_ = gpu::CommandBufferProxyImpl::Create( std::move(channel_), surface_handle_, shared_command_buffer, stream_id_, - stream_priority_, attributes_, active_url_, std::move(task_runner)); + stream_priority_, attributes_, active_url_, task_runner); if (!command_buffer_) { DLOG(ERROR) << "GpuChannelHost failed to create command buffer."; command_buffer_metrics::UmaRecordContextInitFailed(context_type_); @@ -217,6 +216,9 @@ bool ContextProviderCommandBuffer::BindToCurrentThread() { return false; shared_providers_->list.push_back(this); + + cache_controller_.reset(new cc::ContextCacheController( + gles2_impl_.get(), std::move(task_runner))); } set_bind_failed.Reset(); bind_succeeded_ = true; @@ -243,11 +245,13 @@ bool ContextProviderCommandBuffer::BindToCurrentThread() { ContextGL()->TraceBeginCHROMIUM("gpu_toplevel", unique_context_name.c_str()); // If support_locking_ is true, the context may be used from multiple // threads, and any async callstacks will need to hold the same lock, so - // give it to the command buffer. + // give it to the command buffer and cache controller. // We don't hold a lock here since there's no need, so set the lock very last // to prevent asserts that we're not holding it. - if (support_locking_) + if (support_locking_) { command_buffer_->SetLock(&context_lock_); + cache_controller_->SetLock(&context_lock_); + } return true; } @@ -276,6 +280,7 @@ class GrContext* ContextProviderCommandBuffer::GrContext() { return gr_context_->get(); gr_context_.reset(new skia_bindings::GrContextForGLES2Interface(ContextGL())); + cache_controller_->SetGrContext(gr_context_->get()); // If GlContext is already lost, also abandon the new GrContext. if (gr_context_->get() && @@ -285,6 +290,11 @@ class GrContext* ContextProviderCommandBuffer::GrContext() { return gr_context_->get(); } +cc::ContextCacheController* ContextProviderCommandBuffer::CacheController() { + DCHECK(context_thread_checker_.CalledOnValidThread()); + return cache_controller_.get(); +} + void ContextProviderCommandBuffer::InvalidateGrContext(uint32_t state) { if (gr_context_) { DCHECK(bind_succeeded_); @@ -311,13 +321,6 @@ gpu::Capabilities ContextProviderCommandBuffer::ContextCapabilities() { return gles2_impl_->capabilities(); } -void ContextProviderCommandBuffer::DeleteCachedResources() { - DCHECK(context_thread_checker_.CalledOnValidThread()); - - if (gr_context_) - gr_context_->FreeGpuResources(); -} - void ContextProviderCommandBuffer::OnLostContext() { DCHECK(context_thread_checker_.CalledOnValidThread()); diff --git a/chromium/content/common/gpu/client/context_provider_command_buffer.h b/chromium/content/common/gpu/client/context_provider_command_buffer.h index 9ec79ab109c..edc279bbdd0 100644 --- a/chromium/content/common/gpu/client/context_provider_command_buffer.h +++ b/chromium/content/common/gpu/client/context_provider_command_buffer.h @@ -71,10 +71,10 @@ class CONTENT_EXPORT ContextProviderCommandBuffer gpu::gles2::GLES2Interface* ContextGL() override; gpu::ContextSupport* ContextSupport() override; class GrContext* GrContext() override; + cc::ContextCacheController* CacheController() override; void InvalidateGrContext(uint32_t state) override; base::Lock* GetLock() override; gpu::Capabilities ContextCapabilities() override; - void DeleteCachedResources() override; void SetLostContextCallback( const LostContextCallback& lost_context_callback) override; @@ -128,6 +128,7 @@ class CONTENT_EXPORT ContextProviderCommandBuffer std::unique_ptr<gpu::gles2::GLES2Implementation> gles2_impl_; std::unique_ptr<gpu::gles2::GLES2TraceImplementation> trace_impl_; std::unique_ptr<skia_bindings::GrContextForGLES2Interface> gr_context_; + std::unique_ptr<cc::ContextCacheController> cache_controller_; LostContextCallback lost_context_callback_; }; diff --git a/chromium/content/common/gpu_host_messages.h b/chromium/content/common/gpu_host_messages.h index ba7379805f9..2e09001fe30 100644 --- a/chromium/content/common/gpu_host_messages.h +++ b/chromium/content/common/gpu_host_messages.h @@ -12,7 +12,6 @@ #include "gpu/command_buffer/service/gpu_preferences.h" #include "gpu/config/gpu_info.h" #include "gpu/ipc/common/gpu_command_buffer_traits.h" -#include "gpu/ipc/common/gpu_memory_uma_stats.h" #include "gpu/ipc/common/gpu_param_traits.h" #include "gpu/ipc/common/memory_stats.h" #include "gpu/ipc/common/surface_handle.h" @@ -31,15 +30,13 @@ #define IPC_MESSAGE_START GpuMsgStart -IPC_STRUCT_TRAITS_BEGIN(gpu::GPUMemoryUmaStats) - IPC_STRUCT_TRAITS_MEMBER(bytes_allocated_current) - IPC_STRUCT_TRAITS_MEMBER(bytes_allocated_max) -IPC_STRUCT_TRAITS_END() +IPC_ENUM_TRAITS_VALIDATE(gpu::GpuPreferences::VpxDecodeVendors, + ((value >= gpu::GpuPreferences::VPX_VENDOR_NONE) && + (value <= gpu::GpuPreferences::VPX_VENDOR_ALL))) IPC_STRUCT_TRAITS_BEGIN(gpu::VideoMemoryUsageStats) IPC_STRUCT_TRAITS_MEMBER(process_map) IPC_STRUCT_TRAITS_MEMBER(bytes_allocated) - IPC_STRUCT_TRAITS_MEMBER(bytes_allocated_historical_max) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(gpu::VideoMemoryUsageStats::ProcessStats) @@ -165,9 +162,6 @@ IPC_MESSAGE_CONTROL0(GpuMsg_Crash) // Tells the GPU process to hang. IPC_MESSAGE_CONTROL0(GpuMsg_Hang) -// Tells the GPU process to disable the watchdog thread. -IPC_MESSAGE_CONTROL0(GpuMsg_DisableWatchdog) - // Tells the GPU process that the browser has seen a GPU switch. IPC_MESSAGE_CONTROL0(GpuMsg_GpuSwitched) @@ -230,10 +224,6 @@ IPC_MESSAGE_CONTROL3(GpuHostMsg_DidLoseContext, IPC_MESSAGE_CONTROL1(GpuHostMsg_DidDestroyOffscreenContext, GURL /* url */) -// Tells the browser about GPU memory usage statistics for UMA logging. -IPC_MESSAGE_CONTROL1(GpuHostMsg_GpuMemoryUmaStats, - gpu::GPUMemoryUmaStats /* GPU memory UMA stats */) - // Message from GPU to add a GPU log message to the about:gpu page. IPC_MESSAGE_CONTROL3(GpuHostMsg_OnLogMessage, int /*severity*/, diff --git a/chromium/content/common/gpu_process_launch_causes.h b/chromium/content/common/gpu_process_launch_causes.h deleted file mode 100644 index dba1ced2bf1..00000000000 --- a/chromium/content/common/gpu_process_launch_causes.h +++ /dev/null @@ -1,43 +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_COMMON_GPU_PROCESS_LAUNCH_CAUSES_H_ -#define CONTENT_COMMON_GPU_PROCESS_LAUNCH_CAUSES_H_ - -namespace content { - -// If you change this enum you also need to update -// tools/metrics/histograms/histograms.xml -enum CauseForGpuLaunch { - // Start enum from 2 to keep the same values for the histogram. - CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED = 2, - CAUSE_FOR_GPU_LAUNCH_RENDERWIDGETFULLSCREENPEPPER_CREATECONTEXT, - // Deprecated - // CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE, - CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH = 4, - CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE, - CAUSE_FOR_GPU_LAUNCH_PEPPERPLATFORMCONTEXT3DIMPL_INITIALIZE, - CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP, - CAUSE_FOR_GPU_LAUNCH_CANVAS_2D, - CAUSE_FOR_GPU_LAUNCH_PEPPERVIDEOENCODERACCELERATOR_INITIALIZE, - CAUSE_FOR_GPU_LAUNCH_GPU_MEMORY_BUFFER_ALLOCATE, - CAUSE_FOR_GPU_LAUNCH_JPEGDECODEACCELERATOR_INITIALIZE, - CAUSE_FOR_GPU_LAUNCH_MOJO_SETUP, - CAUSE_FOR_GPU_LAUNCH_GET_GPU_SERVICE_REGISTRY, - CAUSE_FOR_GPU_LAUNCH_BROWSER_SHARED_MAIN_THREAD_CONTEXT, - CAUSE_FOR_GPU_LAUNCH_RENDERER_SHARED_MAIN_THREAD_CONTEXT, - CAUSE_FOR_GPU_LAUNCH_WEBGL_CONTEXT, - CAUSE_FOR_GPU_LAUNCH_SHARED_WORKER_THREAD_CONTEXT, - CAUSE_FOR_GPU_LAUNCH_RENDERER_VERIFY_GPU_COMPOSITING, - CAUSE_FOR_GPU_LAUNCH_DISPLAY_COMPOSITOR_CONTEXT, - CAUSE_FOR_GPU_LAUNCH_MEDIA_CONTEXT, - - // All new values should be inserted above this point so that - // existing values continue to match up with those in histograms.xml. - CAUSE_FOR_GPU_LAUNCH_MAX_ENUM -}; - -} // namespace content - -#endif // CONTENT_COMMON_GPU_PROCESS_LAUNCH_CAUSES_H_ diff --git a/chromium/content/common/host_discardable_shared_memory_manager.cc b/chromium/content/common/host_discardable_shared_memory_manager.cc index bfb68905494..e349fca4171 100644 --- a/chromium/content/common/host_discardable_shared_memory_manager.cc +++ b/chromium/content/common/host_discardable_shared_memory_manager.cc @@ -14,6 +14,7 @@ #include "base/lazy_instance.h" #include "base/macros.h" #include "base/memory/discardable_memory.h" +#include "base/memory/memory_coordinator_client_registry.h" #include "base/memory/ptr_util.h" #include "base/numerics/safe_math.h" #include "base/process/memory.h" @@ -33,7 +34,7 @@ #if defined(OS_LINUX) #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #endif namespace content { @@ -163,7 +164,8 @@ HostDiscardableSharedMemoryManager::MemorySegment::~MemorySegment() { } HostDiscardableSharedMemoryManager::HostDiscardableSharedMemoryManager() - : memory_limit_(GetDefaultMemoryLimit()), + : default_memory_limit_(GetDefaultMemoryLimit()), + memory_limit_(default_memory_limit_), bytes_allocated_(0), memory_pressure_listener_(new base::MemoryPressureListener( base::Bind(&HostDiscardableSharedMemoryManager::OnMemoryPressure, @@ -177,7 +179,9 @@ HostDiscardableSharedMemoryManager::HostDiscardableSharedMemoryManager() base::Bind(&HostDiscardableSharedMemoryManager::EnforceMemoryPolicy, weak_ptr_factory_.GetWeakPtr()); base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( - this, "HostDiscardableSharedMemoryManager", nullptr); + this, "HostDiscardableSharedMemoryManager", + base::ThreadTaskRunnerHandle::Get()); + base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this); } HostDiscardableSharedMemoryManager::~HostDiscardableSharedMemoryManager() { @@ -193,8 +197,7 @@ HostDiscardableSharedMemoryManager::current() { std::unique_ptr<base::DiscardableMemory> HostDiscardableSharedMemoryManager::AllocateLockedDiscardableMemory( size_t size) { - // TODO(reveman): Temporary diagnostics for http://crbug.com/577786. - CHECK_NE(size, 0u); + DCHECK_NE(size, 0u); DiscardableSharedMemoryId new_id = g_next_discardable_shared_memory_id.GetNext(); @@ -212,11 +215,11 @@ HostDiscardableSharedMemoryManager::AllocateLockedDiscardableMemory( base::TerminateBecauseOutOfMemory(size); // Close file descriptor to avoid running out. memory->Close(); - return base::WrapUnique(new DiscardableMemoryImpl( + return base::MakeUnique<DiscardableMemoryImpl>( std::move(memory), base::Bind( &HostDiscardableSharedMemoryManager::DeletedDiscardableSharedMemory, - base::Unretained(this), new_id, ChildProcessHost::kInvalidUniqueID))); + base::Unretained(this), new_id, ChildProcessHost::kInvalidUniqueID)); } bool HostDiscardableSharedMemoryManager::OnMemoryDump( @@ -346,6 +349,24 @@ size_t HostDiscardableSharedMemoryManager::GetBytesAllocated() { return bytes_allocated_; } +void HostDiscardableSharedMemoryManager::OnMemoryStateChange( + base::MemoryState state) { + switch (state) { + case base::MemoryState::NORMAL: + SetMemoryLimit(default_memory_limit_); + break; + case base::MemoryState::THROTTLED: + SetMemoryLimit(0); + break; + case base::MemoryState::SUSPENDED: + // Note that SUSPENDED never occurs in the main browser process so far. + // Fall through. + case base::MemoryState::UNKNOWN: + NOTREACHED(); + break; + } +} + void HostDiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory( base::ProcessHandle process_handle, int client_process_id, diff --git a/chromium/content/common/host_discardable_shared_memory_manager.h b/chromium/content/common/host_discardable_shared_memory_manager.h index fcbb35ae8ee..59a939a0297 100644 --- a/chromium/content/common/host_discardable_shared_memory_manager.h +++ b/chromium/content/common/host_discardable_shared_memory_manager.h @@ -17,6 +17,7 @@ #include "base/macros.h" #include "base/memory/discardable_memory_allocator.h" #include "base/memory/discardable_shared_memory.h" +#include "base/memory/memory_coordinator_client.h" #include "base/memory/memory_pressure_listener.h" #include "base/memory/ref_counted.h" #include "base/memory/shared_memory.h" @@ -35,7 +36,8 @@ typedef int32_t DiscardableSharedMemoryId; // This class is thread-safe and instances can safely be used on any thread. class CONTENT_EXPORT HostDiscardableSharedMemoryManager : public base::DiscardableMemoryAllocator, - public base::trace_event::MemoryDumpProvider { + public base::trace_event::MemoryDumpProvider, + public base::MemoryCoordinatorClient { public: HostDiscardableSharedMemoryManager(); ~HostDiscardableSharedMemoryManager() override; @@ -103,6 +105,9 @@ class CONTENT_EXPORT HostDiscardableSharedMemoryManager return a->memory()->last_known_usage() > b->memory()->last_known_usage(); } + // base::MemoryCoordinatorClient implementation: + void OnMemoryStateChange(base::MemoryState state) override; + void AllocateLockedDiscardableSharedMemory( base::ProcessHandle process_handle, int client_process_id, @@ -131,6 +136,7 @@ class CONTENT_EXPORT HostDiscardableSharedMemoryManager // a heap. The LRU memory segment always first. typedef std::vector<scoped_refptr<MemorySegment>> MemorySegmentVector; MemorySegmentVector segments_; + size_t default_memory_limit_; size_t memory_limit_; size_t bytes_allocated_; std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_; diff --git a/chromium/content/common/host_shared_bitmap_manager.cc b/chromium/content/common/host_shared_bitmap_manager.cc index 3a51de6d15e..51f4fc79160 100644 --- a/chromium/content/common/host_shared_bitmap_manager.cc +++ b/chromium/content/common/host_shared_bitmap_manager.cc @@ -125,8 +125,7 @@ std::unique_ptr<cc::SharedBitmap> HostSharedBitmapManager::AllocateSharedBitmap( cc::SharedBitmapId id = cc::SharedBitmap::GenerateId(); handle_map_[id] = data; - return base::WrapUnique( - new HostSharedBitmap(data->pixels.get(), data, id, this)); + return base::MakeUnique<HostSharedBitmap>(data->pixels.get(), data, id, this); } std::unique_ptr<cc::SharedBitmap> @@ -145,15 +144,15 @@ HostSharedBitmapManager::GetSharedBitmapFromId(const gfx::Size& size, return std::unique_ptr<cc::SharedBitmap>(); if (data->pixels) { - return base::WrapUnique( - new HostSharedBitmap(data->pixels.get(), data, id, nullptr)); + return base::MakeUnique<HostSharedBitmap>(data->pixels.get(), data, id, + nullptr); } if (!data->memory->memory()) { return std::unique_ptr<cc::SharedBitmap>(); } - return base::WrapUnique(new HostSharedBitmap( - static_cast<uint8_t*>(data->memory->memory()), data, id, nullptr)); + return base::MakeUnique<HostSharedBitmap>( + static_cast<uint8_t*>(data->memory->memory()), data, id, nullptr); } bool HostSharedBitmapManager::OnMemoryDump( @@ -194,7 +193,7 @@ bool HostSharedBitmapManager::ChildAllocatedSharedBitmap( scoped_refptr<BitmapData> data(new BitmapData(buffer_size)); handle_map_[id] = data; - data->memory = base::WrapUnique(new base::SharedMemory(handle, false)); + data->memory = base::MakeUnique<base::SharedMemory>(handle, false); data->memory->Map(data->buffer_size); data->memory->Close(); return true; diff --git a/chromium/content/common/in_process_child_thread_params.cc b/chromium/content/common/in_process_child_thread_params.cc index 47e0fd9404a..02dc1b4dcd9 100644 --- a/chromium/content/common/in_process_child_thread_params.cc +++ b/chromium/content/common/in_process_child_thread_params.cc @@ -7,12 +7,9 @@ namespace content { InProcessChildThreadParams::InProcessChildThreadParams( - const std::string& channel_name, scoped_refptr<base::SequencedTaskRunner> io_runner, - const std::string& ipc_token, - const std::string& application_token) - : channel_name_(channel_name), io_runner_(io_runner), ipc_token_(ipc_token), - application_token_(application_token) {} + const std::string& service_request_token) + : io_runner_(io_runner), service_request_token_(service_request_token) {} InProcessChildThreadParams::InProcessChildThreadParams( const InProcessChildThreadParams& other) = default; diff --git a/chromium/content/common/in_process_child_thread_params.h b/chromium/content/common/in_process_child_thread_params.h index ebbf8f6f2fc..664db42b51f 100644 --- a/chromium/content/common/in_process_child_thread_params.h +++ b/chromium/content/common/in_process_child_thread_params.h @@ -18,28 +18,21 @@ namespace content { // ChnanelMojo, an IPC channel name to open. class CONTENT_EXPORT InProcessChildThreadParams { public: - InProcessChildThreadParams( - const std::string& channel_name, - scoped_refptr<base::SequencedTaskRunner> io_runner, - const std::string& ipc_token = std::string(), - const std::string& application_token = std::string()); + InProcessChildThreadParams(scoped_refptr<base::SequencedTaskRunner> io_runner, + const std::string& service_request_token); InProcessChildThreadParams(const InProcessChildThreadParams& other); ~InProcessChildThreadParams(); - const std::string& channel_name() const { return channel_name_; } scoped_refptr<base::SequencedTaskRunner> io_runner() const { return io_runner_; } - const std::string& ipc_token() const { return ipc_token_; } - const std::string& application_token() const { - return application_token_; + const std::string& service_request_token() const { + return service_request_token_; } private: - std::string channel_name_; scoped_refptr<base::SequencedTaskRunner> io_runner_; - std::string ipc_token_; - std::string application_token_; + std::string service_request_token_; }; } // namespace content diff --git a/chromium/content/common/indexed_db/OWNERS b/chromium/content/common/indexed_db/OWNERS index c94a62539a2..442406e4f56 100644 --- a/chromium/content/common/indexed_db/OWNERS +++ b/chromium/content/common/indexed_db/OWNERS @@ -1,7 +1,4 @@ -dgrogan@chromium.org -michaeln@chromium.org -jsbell@chromium.org -cmumford@chromium.org +file://content/browser/indexed_db/OWNERS per-file *_messages*.h=set noparent per-file *_messages*.h=file://ipc/SECURITY_OWNERS diff --git a/chromium/content/common/indexed_db/indexed_db_messages.h b/chromium/content/common/indexed_db/indexed_db_messages.h index 68af020df66..0bb208dd500 100644 --- a/chromium/content/common/indexed_db/indexed_db_messages.h +++ b/chromium/content/common/indexed_db/indexed_db_messages.h @@ -6,6 +6,7 @@ #include <stdint.h> +#include <map> #include <string> #include <utility> #include <vector> @@ -14,7 +15,10 @@ #include "content/common/indexed_db/indexed_db_key_path.h" #include "content/common/indexed_db/indexed_db_key_range.h" #include "content/common/indexed_db/indexed_db_param_traits.h" +#include "content/public/common/common_param_traits.h" +#include "content/public/common/common_param_traits_macros.h" #include "ipc/ipc_message_macros.h" +#include "ipc/ipc_message_utils.h" #include "ipc/ipc_param_traits.h" #include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h" #include "url/origin.h" @@ -24,7 +28,12 @@ #define CONTENT_COMMON_INDEXED_DB_INDEXED_DB_MESSAGES_H_ // An index id, and corresponding set of keys to insert. + typedef std::pair<int64_t, std::vector<content::IndexedDBKey>> IndexKeys; +// IPC_MESSAGE macros fail on the std::map, when expanding. We need to define +// a type to avoid that. +// Map observer_id to corresponding set of indices in observations. +typedef std::map<int32_t, std::vector<int32_t>> ObservationIndex; #endif // CONTENT_COMMON_INDEXED_DB_INDEXED_DB_MESSAGES_H_ @@ -42,6 +51,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(blink::WebIDBTransactionMode, blink::WebIDBTransactionModeLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebIDBDataLoss, blink::WebIDBDataLossTotal) +IPC_ENUM_TRAITS_MAX_VALUE(blink::WebIDBOperationType, + blink::WebIDBOperationTypeLast) // Used to enumerate indexed databases. IPC_STRUCT_BEGIN(IndexedDBHostMsg_FactoryGetDatabaseNames_Params) @@ -87,8 +98,6 @@ IPC_STRUCT_BEGIN(IndexedDBHostMsg_DatabaseCreateTransaction_Params) IPC_STRUCT_MEMBER(int32_t, ipc_database_id) // The transaction id as minted by the frontend. IPC_STRUCT_MEMBER(int64_t, transaction_id) - // To get to WebIDBDatabaseCallbacks. - IPC_STRUCT_MEMBER(int32_t, ipc_database_callbacks_id) // The scope of the transaction. IPC_STRUCT_MEMBER(std::vector<int64_t>, object_store_ids) // The transaction mode. @@ -173,6 +182,19 @@ IPC_STRUCT_BEGIN_WITH_PARENT(IndexedDBMsg_ReturnValue, IndexedDBMsg_Value) IPC_STRUCT_MEMBER(content::IndexedDBKeyPath, key_path) IPC_STRUCT_END() +// WebIDBDatabase::observe() message. +IPC_STRUCT_BEGIN(IndexedDBHostMsg_DatabaseObserve_Params) + // The database the observer observers on. + IPC_STRUCT_MEMBER(int32_t, ipc_database_id) + // The transaction it's associated with. + IPC_STRUCT_MEMBER(int32_t, transaction_id) + IPC_STRUCT_MEMBER(int32_t, observer_id) + IPC_STRUCT_MEMBER(bool, include_transaction) + IPC_STRUCT_MEMBER(bool, no_records) + IPC_STRUCT_MEMBER(bool, values) + IPC_STRUCT_MEMBER(uint16_t, operation_types) +IPC_STRUCT_END() + // Used to set a value in an object store. IPC_STRUCT_BEGIN(IndexedDBHostMsg_DatabasePut_Params) // The id any response should contain. @@ -358,6 +380,17 @@ IPC_STRUCT_BEGIN(IndexedDBMsg_CallbacksUpgradeNeeded_Params) IPC_STRUCT_MEMBER(IndexedDBDatabaseMetadata, idb_metadata) IPC_STRUCT_END() +IPC_STRUCT_BEGIN(IndexedDBMsg_Observation) + IPC_STRUCT_MEMBER(int64_t, object_store_id) + IPC_STRUCT_MEMBER(blink::WebIDBOperationType, type) + IPC_STRUCT_MEMBER(content::IndexedDBKeyRange, key_range) +IPC_STRUCT_END() + +IPC_STRUCT_BEGIN(IndexedDBMsg_ObserverChanges) + IPC_STRUCT_MEMBER(ObservationIndex, observation_index) + IPC_STRUCT_MEMBER(std::vector<IndexedDBMsg_Observation>, observations) +IPC_STRUCT_END() + // Indexed DB messages sent from the browser to the renderer. // The thread_id needs to be the first parameter in these messages. In the IO @@ -410,9 +443,6 @@ IPC_MESSAGE_CONTROL4(IndexedDBMsg_CallbacksError, int32_t /* ipc_callbacks_id */, int /* code */, base::string16 /* message */) -IPC_MESSAGE_CONTROL2(IndexedDBMsg_CallbacksBlocked, - int32_t /* ipc_thread_id */, - int32_t /* ipc_callbacks_id */) IPC_MESSAGE_CONTROL3(IndexedDBMsg_CallbacksIntBlocked, int32_t /* ipc_thread_id */, int32_t /* ipc_callbacks_id */, @@ -439,6 +469,10 @@ IPC_MESSAGE_CONTROL3(IndexedDBMsg_DatabaseCallbacksComplete, int32_t, /* ipc_thread_id */ int32_t, /* ipc_database_callbacks_id */ int64_t) /* transaction_id */ +IPC_MESSAGE_CONTROL3(IndexedDBMsg_DatabaseCallbacksChanges, + int32_t, /* ipc_thread_id */ + int32_t, /* ipc_database_id */ + IndexedDBMsg_ObserverChanges) // Indexed DB messages sent from the renderer to the browser. @@ -485,6 +519,11 @@ IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_FactoryDeleteDatabase, IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_AckReceivedBlobs, std::vector<std::string>) /* uuids */ +// WebIDBDatabase::unobserve() message. +IPC_MESSAGE_CONTROL2(IndexedDBHostMsg_DatabaseUnobserve, + int32_t, /* ipc_database_id */ + std::vector<int32_t>) /* list of observer_id */ + // WebIDBDatabase::createObjectStore() message. IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabaseCreateObjectStore, IndexedDBHostMsg_DatabaseCreateObjectStore_Params) @@ -495,6 +534,13 @@ IPC_MESSAGE_CONTROL3(IndexedDBHostMsg_DatabaseDeleteObjectStore, int64_t, /* transaction_id */ int64_t) /* object_store_id */ +// WebIDBDatabase::renameObjectStore() message. +IPC_MESSAGE_CONTROL4(IndexedDBHostMsg_DatabaseRenameObjectStore, + int32_t, /* ipc_database_id */ + int64_t, /* transaction_id */ + int64_t, /* object_store_id */ + base::string16) /* new_name */ + // WebIDBDatabase::createTransaction() message. IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabaseCreateTransaction, IndexedDBHostMsg_DatabaseCreateTransaction_Params) @@ -519,6 +565,10 @@ IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabaseGet, IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabaseGetAll, IndexedDBHostMsg_DatabaseGetAll_Params) +// WebIDBDatabase::observe() message. +IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabaseObserve, + IndexedDBHostMsg_DatabaseObserve_Params) + // WebIDBDatabase::put() message. IPC_MESSAGE_CONTROL1(IndexedDBHostMsg_DatabasePut, IndexedDBHostMsg_DatabasePut_Params) @@ -565,6 +615,14 @@ IPC_MESSAGE_CONTROL4(IndexedDBHostMsg_DatabaseDeleteIndex, int64_t, /* object_store_id */ int64_t) /* index_id */ +// WebIDBDatabase::renameIndex() message. +IPC_MESSAGE_CONTROL5(IndexedDBHostMsg_DatabaseRenameIndex, + int32_t, /* ipc_database_id */ + int64_t, /* transaction_id */ + int64_t, /* object_store_id */ + int64_t, /* index_id */ + base::string16) /* new_name */ + // WebIDBDatabase::abort() message. IPC_MESSAGE_CONTROL2(IndexedDBHostMsg_DatabaseAbort, int32_t, /* ipc_database_id */ diff --git a/chromium/content/common/input/OWNERS b/chromium/content/common/input/OWNERS index 6039fc41d10..368b47fb459 100644 --- a/chromium/content/common/input/OWNERS +++ b/chromium/content/common/input/OWNERS @@ -1,2 +1,6 @@ aelias@chromium.org +dtapuska@chromium.org tdresser@chromium.org + +per-file *_param_traits*.*=set noparent +per-file *_param_traits*.*=file://ipc/SECURITY_OWNERS
\ No newline at end of file diff --git a/chromium/content/common/input/did_overscroll_params.cc b/chromium/content/common/input/did_overscroll_params.cc deleted file mode 100644 index 2b69d8600e7..00000000000 --- a/chromium/content/common/input/did_overscroll_params.cc +++ /dev/null @@ -1,15 +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/common/input/did_overscroll_params.h" - -namespace content { - -DidOverscrollParams::DidOverscrollParams() { -} - -DidOverscrollParams::~DidOverscrollParams() { -} - -} // namespace content diff --git a/chromium/content/common/input/did_overscroll_params.h b/chromium/content/common/input/did_overscroll_params.h deleted file mode 100644 index 7db3ac43009..00000000000 --- a/chromium/content/common/input/did_overscroll_params.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_INPUT_DID_OVERSCROLL_PARAMS_H_ -#define CONTENT_COMMON_INPUT_DID_OVERSCROLL_PARAMS_H_ - -#include "content/common/content_export.h" -#include "ui/gfx/geometry/point_f.h" -#include "ui/gfx/geometry/vector2d_f.h" - -namespace content { - -struct CONTENT_EXPORT DidOverscrollParams { - DidOverscrollParams(); - ~DidOverscrollParams(); - gfx::Vector2dF accumulated_overscroll; - gfx::Vector2dF latest_overscroll_delta; - gfx::Vector2dF current_fling_velocity; - gfx::PointF causal_event_viewport_point; -}; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_DID_OVERSCROLL_PARAMS_H_ diff --git a/chromium/content/common/input/event_with_latency_info.cc b/chromium/content/common/input/event_with_latency_info.cc new file mode 100644 index 00000000000..bafa99e15ad --- /dev/null +++ b/chromium/content/common/input/event_with_latency_info.cc @@ -0,0 +1,303 @@ +// 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/common/input/event_with_latency_info.h" + +#include <bitset> +#include <limits> + +using blink::WebGestureEvent; +using blink::WebInputEvent; +using blink::WebKeyboardEvent; +using blink::WebMouseEvent; +using blink::WebMouseWheelEvent; +using blink::WebTouchEvent; +using std::numeric_limits; + +namespace content { +namespace { + +const int kInvalidTouchIndex = -1; + +float GetUnacceleratedDelta(float accelerated_delta, float acceleration_ratio) { + return accelerated_delta * acceleration_ratio; +} + +float GetAccelerationRatio(float accelerated_delta, float unaccelerated_delta) { + if (unaccelerated_delta == 0.f || accelerated_delta == 0.f) + return 1.f; + return unaccelerated_delta / accelerated_delta; +} + +// Returns |kInvalidTouchIndex| iff |event| lacks a touch with an ID of |id|. +int GetIndexOfTouchID(const WebTouchEvent& event, int id) { + for (unsigned i = 0; i < event.touchesLength; ++i) { + if (event.touches[i].id == id) + return i; + } + return kInvalidTouchIndex; +} + +WebInputEvent::DispatchType MergeDispatchTypes( + WebInputEvent::DispatchType type_1, + WebInputEvent::DispatchType type_2) { + static_assert(WebInputEvent::DispatchType::Blocking < + WebInputEvent::DispatchType::EventNonBlocking, + "Enum not ordered correctly"); + static_assert(WebInputEvent::DispatchType::EventNonBlocking < + WebInputEvent::DispatchType::ListenersNonBlockingPassive, + "Enum not ordered correctly"); + static_assert( + WebInputEvent::DispatchType::ListenersNonBlockingPassive < + WebInputEvent::DispatchType::ListenersForcedNonBlockingDueToFling, + "Enum not ordered correctly"); + return static_cast<WebInputEvent::DispatchType>( + std::min(static_cast<int>(type_1), static_cast<int>(type_2))); +} + +} // namespace + +namespace internal { + +bool CanCoalesce(const WebMouseEvent& event_to_coalesce, + const WebMouseEvent& event) { + return event.type == event_to_coalesce.type && + event.type == WebInputEvent::MouseMove; +} + +void Coalesce(const WebMouseEvent& event_to_coalesce, WebMouseEvent* event) { + DCHECK(CanCoalesce(event_to_coalesce, *event)); + // Accumulate movement deltas. + int x = event->movementX; + int y = event->movementY; + *event = event_to_coalesce; + event->movementX += x; + event->movementY += y; +} + +bool CanCoalesce(const WebMouseWheelEvent& event_to_coalesce, + const WebMouseWheelEvent& event) { + return event.modifiers == event_to_coalesce.modifiers && + event.scrollByPage == event_to_coalesce.scrollByPage && + event.phase == event_to_coalesce.phase && + event.momentumPhase == event_to_coalesce.momentumPhase && + event.hasPreciseScrollingDeltas == + event_to_coalesce.hasPreciseScrollingDeltas; +} + +void Coalesce(const WebMouseWheelEvent& event_to_coalesce, + WebMouseWheelEvent* event) { + DCHECK(CanCoalesce(event_to_coalesce, *event)); + float unaccelerated_x = + GetUnacceleratedDelta(event->deltaX, event->accelerationRatioX) + + GetUnacceleratedDelta(event_to_coalesce.deltaX, + event_to_coalesce.accelerationRatioX); + float unaccelerated_y = + GetUnacceleratedDelta(event->deltaY, event->accelerationRatioY) + + GetUnacceleratedDelta(event_to_coalesce.deltaY, + event_to_coalesce.accelerationRatioY); + float old_deltaX = event->deltaX; + float old_deltaY = event->deltaY; + float old_wheelTicksX = event->wheelTicksX; + float old_wheelTicksY = event->wheelTicksY; + float old_movementX = event->movementX; + float old_movementY = event->movementY; + *event = event_to_coalesce; + event->deltaX += old_deltaX; + event->deltaY += old_deltaY; + event->wheelTicksX += old_wheelTicksX; + event->wheelTicksY += old_wheelTicksY; + event->movementX += old_movementX; + event->movementY += old_movementY; + event->accelerationRatioX = + GetAccelerationRatio(event->deltaX, unaccelerated_x); + event->accelerationRatioY = + GetAccelerationRatio(event->deltaY, unaccelerated_y); +} + +bool CanCoalesce(const WebTouchEvent& event_to_coalesce, + const WebTouchEvent& event) { + if (event.type != event_to_coalesce.type || + event.type != WebInputEvent::TouchMove || + event.modifiers != event_to_coalesce.modifiers || + event.touchesLength != event_to_coalesce.touchesLength || + event.touchesLength > WebTouchEvent::kTouchesLengthCap) + return false; + + static_assert(WebTouchEvent::kTouchesLengthCap <= sizeof(int32_t) * 8U, + "suboptimal kTouchesLengthCap size"); + // Ensure that we have a 1-to-1 mapping of pointer ids between touches. + std::bitset<WebTouchEvent::kTouchesLengthCap> unmatched_event_touches( + (1 << event.touchesLength) - 1); + for (unsigned i = 0; i < event_to_coalesce.touchesLength; ++i) { + int event_touch_index = + GetIndexOfTouchID(event, event_to_coalesce.touches[i].id); + if (event_touch_index == kInvalidTouchIndex) + return false; + if (!unmatched_event_touches[event_touch_index]) + return false; + unmatched_event_touches[event_touch_index] = false; + } + return unmatched_event_touches.none(); +} + +void Coalesce(const WebTouchEvent& event_to_coalesce, WebTouchEvent* event) { + DCHECK(CanCoalesce(event_to_coalesce, *event)); + // The WebTouchPoints include absolute position information. So it is + // sufficient to simply replace the previous event with the new event-> + // However, it is necessary to make sure that all the points have the + // correct state, i.e. the touch-points that moved in the last event, but + // didn't change in the current event, will have Stationary state. It is + // necessary to change them back to Moved state. + WebTouchEvent old_event = *event; + *event = event_to_coalesce; + for (unsigned i = 0; i < event->touchesLength; ++i) { + int i_old = GetIndexOfTouchID(old_event, event->touches[i].id); + if (old_event.touches[i_old].state == blink::WebTouchPoint::StateMoved) + event->touches[i].state = blink::WebTouchPoint::StateMoved; + } + event->movedBeyondSlopRegion |= old_event.movedBeyondSlopRegion; + event->dispatchType = MergeDispatchTypes(old_event.dispatchType, + event_to_coalesce.dispatchType); +} + +bool CanCoalesce(const WebGestureEvent& event_to_coalesce, + const WebGestureEvent& event) { + if (event.type != event_to_coalesce.type || + event.sourceDevice != event_to_coalesce.sourceDevice || + event.modifiers != event_to_coalesce.modifiers) + return false; + + if (event.type == WebInputEvent::GestureScrollUpdate) + return true; + + // GesturePinchUpdate scales can be combined only if they share a focal point, + // e.g., with double-tap drag zoom. + if (event.type == WebInputEvent::GesturePinchUpdate && + event.x == event_to_coalesce.x && event.y == event_to_coalesce.y) + return true; + + return false; +} + +void Coalesce(const WebGestureEvent& event_to_coalesce, + WebGestureEvent* event) { + DCHECK(CanCoalesce(event_to_coalesce, *event)); + if (event->type == WebInputEvent::GestureScrollUpdate) { + event->data.scrollUpdate.deltaX += + event_to_coalesce.data.scrollUpdate.deltaX; + event->data.scrollUpdate.deltaY += + event_to_coalesce.data.scrollUpdate.deltaY; + DCHECK_EQ( + event->data.scrollUpdate.previousUpdateInSequencePrevented, + event_to_coalesce.data.scrollUpdate.previousUpdateInSequencePrevented); + } else if (event->type == WebInputEvent::GesturePinchUpdate) { + event->data.pinchUpdate.scale *= event_to_coalesce.data.pinchUpdate.scale; + // Ensure the scale remains bounded above 0 and below Infinity so that + // we can reliably perform operations like log on the values. + if (event->data.pinchUpdate.scale < numeric_limits<float>::min()) + event->data.pinchUpdate.scale = numeric_limits<float>::min(); + else if (event->data.pinchUpdate.scale > numeric_limits<float>::max()) + event->data.pinchUpdate.scale = numeric_limits<float>::max(); + } +} + +bool CanCoalesce(const blink::WebInputEvent& event_to_coalesce, + const blink::WebInputEvent& event) { + if (blink::WebInputEvent::isGestureEventType(event_to_coalesce.type) && + blink::WebInputEvent::isGestureEventType(event.type)) { + return CanCoalesce( + static_cast<const blink::WebGestureEvent&>(event_to_coalesce), + static_cast<const blink::WebGestureEvent&>(event)); + } + if (blink::WebInputEvent::isMouseEventType(event_to_coalesce.type) && + blink::WebInputEvent::isMouseEventType(event.type)) { + return CanCoalesce( + static_cast<const blink::WebMouseEvent&>(event_to_coalesce), + static_cast<const blink::WebMouseEvent&>(event)); + } + if (blink::WebInputEvent::isTouchEventType(event_to_coalesce.type) && + blink::WebInputEvent::isTouchEventType(event.type)) { + return CanCoalesce( + static_cast<const blink::WebTouchEvent&>(event_to_coalesce), + static_cast<const blink::WebTouchEvent&>(event)); + } + if (event_to_coalesce.type == blink::WebInputEvent::MouseWheel && + event.type == blink::WebInputEvent::MouseWheel) { + return CanCoalesce( + static_cast<const blink::WebMouseWheelEvent&>(event_to_coalesce), + static_cast<const blink::WebMouseWheelEvent&>(event)); + } + return false; +} + +void Coalesce(const blink::WebInputEvent& event_to_coalesce, + blink::WebInputEvent* event) { + if (blink::WebInputEvent::isGestureEventType(event_to_coalesce.type) && + blink::WebInputEvent::isGestureEventType(event->type)) { + Coalesce(static_cast<const blink::WebGestureEvent&>(event_to_coalesce), + static_cast<blink::WebGestureEvent*>(event)); + return; + } + if (blink::WebInputEvent::isMouseEventType(event_to_coalesce.type) && + blink::WebInputEvent::isMouseEventType(event->type)) { + Coalesce(static_cast<const blink::WebMouseEvent&>(event_to_coalesce), + static_cast<blink::WebMouseEvent*>(event)); + return; + } + if (blink::WebInputEvent::isTouchEventType(event_to_coalesce.type) && + blink::WebInputEvent::isTouchEventType(event->type)) { + Coalesce(static_cast<const blink::WebTouchEvent&>(event_to_coalesce), + static_cast<blink::WebTouchEvent*>(event)); + return; + } + if (event_to_coalesce.type == blink::WebInputEvent::MouseWheel && + event->type == blink::WebInputEvent::MouseWheel) { + Coalesce(static_cast<const blink::WebMouseWheelEvent&>(event_to_coalesce), + static_cast<blink::WebMouseWheelEvent*>(event)); + } +} + +} // namespace internal + +ScopedWebInputEventWithLatencyInfo::ScopedWebInputEventWithLatencyInfo( + ui::ScopedWebInputEvent event, + const ui::LatencyInfo& latency_info) + : event_(std::move(event)), latency_(latency_info) { +} + +ScopedWebInputEventWithLatencyInfo::~ScopedWebInputEventWithLatencyInfo() {} + +bool ScopedWebInputEventWithLatencyInfo::CanCoalesceWith( + const ScopedWebInputEventWithLatencyInfo& other) const { + return internal::CanCoalesce(other.event(), event()); +} + +void ScopedWebInputEventWithLatencyInfo::CoalesceWith( + const ScopedWebInputEventWithLatencyInfo& other) { + // |other| should be a newer event than |this|. + if (other.latency_.trace_id() >= 0 && latency_.trace_id() >= 0) + DCHECK_GT(other.latency_.trace_id(), latency_.trace_id()); + + // New events get coalesced into older events, and the newer timestamp + // should always be preserved. + const double time_stamp_seconds = other.event().timeStampSeconds; + internal::Coalesce(other.event(), event_.get()); + event_->timeStampSeconds = time_stamp_seconds; + + // When coalescing two input events, we keep the oldest LatencyInfo + // since it will represent the longest latency. + other.latency_ = latency_; + other.latency_.set_coalesced(); +} + +const blink::WebInputEvent& ScopedWebInputEventWithLatencyInfo::event() const { + return *event_; +} + +blink::WebInputEvent& ScopedWebInputEventWithLatencyInfo::event() { + return *event_; +} + +} // 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 24742a3baeb..021b3bfc8ac 100644 --- a/chromium/content/common/input/event_with_latency_info.h +++ b/chromium/content/common/input/event_with_latency_info.h @@ -5,18 +5,56 @@ #ifndef CONTENT_COMMON_INPUT_EVENT_WITH_LATENCY_INFO_H_ #define CONTENT_COMMON_INPUT_EVENT_WITH_LATENCY_INFO_H_ +#include "base/compiler_specific.h" +#include "base/logging.h" +#include "content/common/content_export.h" +#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/scoped_web_input_event.h" #include "ui/events/latency_info.h" -#include "content/common/input/web_input_event_traits.h" +namespace content { +namespace internal { -namespace blink { -class WebGestureEvent; -class WebMouseEvent; -class WebMouseWheelEvent; -class WebTouchEvent; -} +bool CONTENT_EXPORT CanCoalesce(const blink::WebMouseEvent& event_to_coalesce, + const blink::WebMouseEvent& event); +void CONTENT_EXPORT Coalesce(const blink::WebMouseEvent& event_to_coalesce, + blink::WebMouseEvent* event); +bool CONTENT_EXPORT +CanCoalesce(const blink::WebMouseWheelEvent& event_to_coalesce, + const blink::WebMouseWheelEvent& event); +void CONTENT_EXPORT Coalesce(const blink::WebMouseWheelEvent& event_to_coalesce, + blink::WebMouseWheelEvent* event); +bool CONTENT_EXPORT CanCoalesce(const blink::WebTouchEvent& event_to_coalesce, + const blink::WebTouchEvent& event); +void CONTENT_EXPORT Coalesce(const blink::WebTouchEvent& event_to_coalesce, + blink::WebTouchEvent* event); +bool CONTENT_EXPORT CanCoalesce(const blink::WebGestureEvent& event_to_coalesce, + const blink::WebGestureEvent& event); +void CONTENT_EXPORT Coalesce(const blink::WebGestureEvent& event_to_coalesce, + blink::WebGestureEvent* event); -namespace content { +} // namespace internal + +class ScopedWebInputEventWithLatencyInfo { + public: + ScopedWebInputEventWithLatencyInfo(ui::ScopedWebInputEvent, + const ui::LatencyInfo&); + + ~ScopedWebInputEventWithLatencyInfo(); + + bool CanCoalesceWith(const ScopedWebInputEventWithLatencyInfo& other) const + WARN_UNUSED_RESULT; + + const blink::WebInputEvent& event() const; + blink::WebInputEvent& event(); + const ui::LatencyInfo latencyInfo() const { return latency_; } + + void CoalesceWith(const ScopedWebInputEventWithLatencyInfo& other); + + private: + ui::ScopedWebInputEvent event_; + mutable ui::LatencyInfo latency_; +}; template <typename T> class EventWithLatencyInfo { @@ -33,14 +71,26 @@ class EventWithLatencyInfo { bool CanCoalesceWith(const EventWithLatencyInfo& other) const WARN_UNUSED_RESULT { - return WebInputEventTraits::CanCoalesce(other.event, event); + if (other.event.type != event.type) + return false; + + DCHECK_EQ(sizeof(T), event.size); + DCHECK_EQ(sizeof(T), other.event.size); + + return internal::CanCoalesce(other.event, event); } void CoalesceWith(const EventWithLatencyInfo& other) { // |other| should be a newer event than |this|. if (other.latency.trace_id() >= 0 && latency.trace_id() >= 0) DCHECK_GT(other.latency.trace_id(), latency.trace_id()); - WebInputEventTraits::Coalesce(other.event, &event); + + // New events get coalesced into older events, and the newer timestamp + // should always be preserved. + const double time_stamp_seconds = other.event.timeStampSeconds; + internal::Coalesce(other.event, &event); + event.timeStampSeconds = time_stamp_seconds; + // When coalescing two input events, we keep the oldest LatencyInfo // for Telemetry latency tests, since it will represent the longest // latency. 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 8ae533dd605..ca6baefe42a 100644 --- a/chromium/content/common/input/event_with_latency_info_unittest.cc +++ b/chromium/content/common/input/event_with_latency_info_unittest.cc @@ -4,6 +4,8 @@ #include "content/common/input/event_with_latency_info.h" +#include <limits> + #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/web/WebInputEvent.h" @@ -12,44 +14,54 @@ using blink::WebInputEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; using blink::WebTouchEvent; +using blink::WebTouchPoint; +using std::numeric_limits; namespace content { namespace { -class EventWithLatencyInfoTest : public testing::Test { - protected: - TouchEventWithLatencyInfo CreateTouchEvent(WebInputEvent::Type type, - double timestamp) { - TouchEventWithLatencyInfo touch; - touch.event.touchesLength = 1; - touch.event.type = type; - touch.event.timeStampSeconds = timestamp; - return touch; - } - - MouseEventWithLatencyInfo CreateMouseEvent(WebInputEvent::Type type, - double timestamp) { - MouseEventWithLatencyInfo mouse; - mouse.event.type = type; - mouse.event.timeStampSeconds = timestamp; - return mouse; - } - - MouseWheelEventWithLatencyInfo CreateMouseWheelEvent(double timestamp) { - MouseWheelEventWithLatencyInfo mouse_wheel; - mouse_wheel.event.type = WebInputEvent::MouseWheel; - mouse_wheel.event.timeStampSeconds = timestamp; - return mouse_wheel; - } - - GestureEventWithLatencyInfo CreateGestureEvent(WebInputEvent::Type type, - double timestamp) { - GestureEventWithLatencyInfo gesture; - gesture.event.type = type; - gesture.event.timeStampSeconds = timestamp; - return gesture; - } -}; +using EventWithLatencyInfoTest = testing::Test; + +TouchEventWithLatencyInfo CreateTouchEvent(WebInputEvent::Type type, + double timestamp, + unsigned touch_count = 1) { + TouchEventWithLatencyInfo touch; + touch.event.touchesLength = touch_count; + touch.event.type = type; + touch.event.timeStampSeconds = timestamp; + return touch; +} + +MouseEventWithLatencyInfo CreateMouseEvent(WebInputEvent::Type type, + double timestamp) { + MouseEventWithLatencyInfo mouse; + mouse.event.type = type; + mouse.event.timeStampSeconds = timestamp; + return mouse; +} + +MouseWheelEventWithLatencyInfo CreateMouseWheelEvent(double timestamp, + float deltaX = 0.0f, + float deltaY = 0.0f) { + MouseWheelEventWithLatencyInfo mouse_wheel; + mouse_wheel.event.type = WebInputEvent::MouseWheel; + mouse_wheel.event.deltaX = deltaX; + mouse_wheel.event.deltaY = deltaY; + mouse_wheel.event.timeStampSeconds = timestamp; + return mouse_wheel; +} + +GestureEventWithLatencyInfo CreateGestureEvent(WebInputEvent::Type type, + double timestamp, + float x = 0.0f, + float y = 0.0f) { + GestureEventWithLatencyInfo gesture; + gesture.event.type = type; + gesture.event.x = x; + gesture.event.y = y; + gesture.event.timeStampSeconds = timestamp; + return gesture; +} TEST_F(EventWithLatencyInfoTest, TimestampCoalescingForMouseEvent) { MouseEventWithLatencyInfo mouse_0 = CreateMouseEvent( @@ -118,5 +130,240 @@ TEST_F(EventWithLatencyInfoTest, LatencyInfoCoalescing) { ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0, &component)); } +WebTouchPoint CreateTouchPoint(WebTouchPoint::State state, int id) { + WebTouchPoint touch; + touch.state = state; + touch.id = id; + return touch; +} + +TouchEventWithLatencyInfo CreateTouch(WebInputEvent::Type type, + unsigned touch_count = 1) { + return CreateTouchEvent(type, 0.0, touch_count); +} + +GestureEventWithLatencyInfo CreateGesture(WebInputEvent::Type type, + float x, + float y) { + return CreateGestureEvent(type, 0.0, x, y); +} + +MouseWheelEventWithLatencyInfo CreateMouseWheel(float deltaX, float deltaY) { + return CreateMouseWheelEvent(0.0, deltaX, deltaY); +} + +template <class T> +bool CanCoalesce(const T& event_to_coalesce, const T& event) { + return event.CanCoalesceWith(event_to_coalesce); +} + +template <class T> +void Coalesce(const T& event_to_coalesce, T* event) { + return event->CoalesceWith(event_to_coalesce); +} + +TEST_F(EventWithLatencyInfoTest, TouchEventCoalescing) { + TouchEventWithLatencyInfo touch0 = CreateTouch(WebInputEvent::TouchStart); + TouchEventWithLatencyInfo touch1 = CreateTouch(WebInputEvent::TouchMove); + + // Non touch-moves won't coalesce. + EXPECT_FALSE(CanCoalesce(touch0, touch0)); + + // Touches of different types won't coalesce. + EXPECT_FALSE(CanCoalesce(touch0, touch1)); + + // Touch moves with idential touch lengths and touch ids should coalesce. + EXPECT_TRUE(CanCoalesce(touch1, touch1)); + + // Touch moves with different touch ids should not coalesce. + touch0 = CreateTouch(WebInputEvent::TouchMove); + touch1 = CreateTouch(WebInputEvent::TouchMove); + touch0.event.touches[0].id = 7; + EXPECT_FALSE(CanCoalesce(touch0, touch1)); + touch0 = CreateTouch(WebInputEvent::TouchMove, 2); + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.touches[0].id = 1; + touch1.event.touches[0].id = 0; + EXPECT_FALSE(CanCoalesce(touch0, touch1)); + + // Touch moves with different touch lengths should not coalesce. + touch0 = CreateTouch(WebInputEvent::TouchMove, 1); + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + EXPECT_FALSE(CanCoalesce(touch0, touch1)); + + // Touch moves with identical touch ids in different orders should coalesce. + touch0 = CreateTouch(WebInputEvent::TouchMove, 2); + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.touches[0] = touch1.event.touches[1] = + CreateTouchPoint(WebTouchPoint::StateMoved, 1); + touch0.event.touches[1] = touch1.event.touches[0] = + CreateTouchPoint(WebTouchPoint::StateMoved, 0); + EXPECT_TRUE(CanCoalesce(touch0, touch1)); + + // Pointers with the same ID's should coalesce. + touch0 = CreateTouch(WebInputEvent::TouchMove, 2); + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.touches[0] = touch1.event.touches[1] = + CreateTouchPoint(WebTouchPoint::StateMoved, 1); + Coalesce(touch0, &touch1); + ASSERT_EQ(1, touch1.event.touches[0].id); + ASSERT_EQ(0, touch1.event.touches[1].id); + EXPECT_EQ(WebTouchPoint::StateUndefined, touch1.event.touches[1].state); + EXPECT_EQ(WebTouchPoint::StateMoved, touch1.event.touches[0].state); + + // Movement from now-stationary pointers should be preserved. + touch0 = touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.touches[0] = CreateTouchPoint(WebTouchPoint::StateMoved, 1); + touch1.event.touches[1] = CreateTouchPoint(WebTouchPoint::StateStationary, 1); + touch0.event.touches[1] = CreateTouchPoint(WebTouchPoint::StateStationary, 0); + touch1.event.touches[0] = CreateTouchPoint(WebTouchPoint::StateMoved, 0); + Coalesce(touch0, &touch1); + ASSERT_EQ(1, touch1.event.touches[0].id); + ASSERT_EQ(0, touch1.event.touches[1].id); + EXPECT_EQ(WebTouchPoint::StateMoved, touch1.event.touches[0].state); + EXPECT_EQ(WebTouchPoint::StateMoved, touch1.event.touches[1].state); + + // Touch moves with different dispatchTypes coalesce. + touch0 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.dispatchType = WebInputEvent::DispatchType::Blocking; + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch1.event.dispatchType = WebInputEvent::DispatchType::EventNonBlocking; + touch0.event.touches[0] = touch1.event.touches[1] = + CreateTouchPoint(WebTouchPoint::StateMoved, 1); + touch0.event.touches[1] = touch1.event.touches[0] = + CreateTouchPoint(WebTouchPoint::StateMoved, 0); + EXPECT_TRUE(CanCoalesce(touch0, touch1)); + Coalesce(touch0, &touch1); + ASSERT_EQ(WebInputEvent::DispatchType::Blocking, touch1.event.dispatchType); + + touch0 = CreateTouch(WebInputEvent::TouchMove, 2); + touch0.event.dispatchType = + WebInputEvent::DispatchType::ListenersForcedNonBlockingDueToFling; + touch1 = CreateTouch(WebInputEvent::TouchMove, 2); + touch1.event.dispatchType = + WebInputEvent::DispatchType::ListenersNonBlockingPassive; + touch0.event.touches[0] = touch1.event.touches[1] = + CreateTouchPoint(WebTouchPoint::StateMoved, 1); + touch0.event.touches[1] = touch1.event.touches[0] = + CreateTouchPoint(WebTouchPoint::StateMoved, 0); + EXPECT_TRUE(CanCoalesce(touch0, touch1)); + Coalesce(touch0, &touch1); + ASSERT_EQ(WebInputEvent::DispatchType::ListenersNonBlockingPassive, + touch1.event.dispatchType); +} + +TEST_F(EventWithLatencyInfoTest, PinchEventCoalescing) { + GestureEventWithLatencyInfo pinch0 = + CreateGesture(WebInputEvent::GesturePinchBegin, 1, 1); + GestureEventWithLatencyInfo pinch1 = + CreateGesture(WebInputEvent::GesturePinchUpdate, 2, 2); + + // Only GesturePinchUpdate's coalesce. + EXPECT_FALSE(CanCoalesce(pinch0, pinch0)); + + // Pinch gestures of different types should not coalesce. + EXPECT_FALSE(CanCoalesce(pinch0, pinch1)); + + // Pinches with different focal points should not coalesce. + pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 2, 2); + EXPECT_FALSE(CanCoalesce(pinch0, pinch1)); + EXPECT_TRUE(CanCoalesce(pinch0, pinch0)); + + // Coalesced scales are multiplicative. + pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch0.event.data.pinchUpdate.scale = 2.f; + pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch1.event.data.pinchUpdate.scale = 3.f; + EXPECT_TRUE(CanCoalesce(pinch0, pinch0)); + Coalesce(pinch0, &pinch1); + EXPECT_EQ(2.f * 3.f, pinch1.event.data.pinchUpdate.scale); + + // Scales have a minimum value and can never reach 0. + ASSERT_GT(numeric_limits<float>::min(), 0); + pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch0.event.data.pinchUpdate.scale = numeric_limits<float>::min() * 2.0f; + pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch1.event.data.pinchUpdate.scale = numeric_limits<float>::min() * 5.0f; + EXPECT_TRUE(CanCoalesce(pinch0, pinch1)); + Coalesce(pinch0, &pinch1); + EXPECT_EQ(numeric_limits<float>::min(), pinch1.event.data.pinchUpdate.scale); + + // Scales have a maximum value and can never reach Infinity. + pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch0.event.data.pinchUpdate.scale = numeric_limits<float>::max() / 2.0f; + pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); + pinch1.event.data.pinchUpdate.scale = 10.0f; + EXPECT_TRUE(CanCoalesce(pinch0, pinch1)); + Coalesce(pinch0, &pinch1); + EXPECT_EQ(numeric_limits<float>::max(), pinch1.event.data.pinchUpdate.scale); +} + +TEST_F(EventWithLatencyInfoTest, WebMouseWheelEventCoalescing) { + MouseWheelEventWithLatencyInfo mouse_wheel_0 = CreateMouseWheel(1, 1); + MouseWheelEventWithLatencyInfo mouse_wheel_1 = CreateMouseWheel(2, 2); + // WebMouseWheelEvent objects with same values except different deltaX and + // deltaY should coalesce. + EXPECT_TRUE(CanCoalesce(mouse_wheel_0, mouse_wheel_1)); + + // WebMouseWheelEvent objects with different modifiers should not coalesce. + mouse_wheel_0 = CreateMouseWheel(1, 1); + mouse_wheel_1 = CreateMouseWheel(1, 1); + mouse_wheel_0.event.modifiers = WebInputEvent::ControlKey; + mouse_wheel_1.event.modifiers = WebInputEvent::ShiftKey; + EXPECT_FALSE(CanCoalesce(mouse_wheel_0, mouse_wheel_1)); + + // Coalesce old and new events. + mouse_wheel_0 = CreateMouseWheel(1, 1); + mouse_wheel_0.event.x = 1; + mouse_wheel_0.event.y = 1; + mouse_wheel_1 = CreateMouseWheel(2, 2); + mouse_wheel_1.event.x = 2; + mouse_wheel_1.event.y = 2; + MouseWheelEventWithLatencyInfo mouse_wheel_1_copy = mouse_wheel_1; + EXPECT_TRUE(CanCoalesce(mouse_wheel_0, mouse_wheel_1)); + EXPECT_EQ(mouse_wheel_0.event.modifiers, mouse_wheel_1.event.modifiers); + EXPECT_EQ(mouse_wheel_0.event.scrollByPage, mouse_wheel_1.event.scrollByPage); + EXPECT_EQ(mouse_wheel_0.event.phase, mouse_wheel_1.event.phase); + EXPECT_EQ(mouse_wheel_0.event.momentumPhase, + mouse_wheel_1.event.momentumPhase); + EXPECT_EQ(mouse_wheel_0.event.hasPreciseScrollingDeltas, + mouse_wheel_1.event.hasPreciseScrollingDeltas); + Coalesce(mouse_wheel_0, &mouse_wheel_1); + + // Coalesced event has the position of the most recent event. + EXPECT_EQ(1, mouse_wheel_1.event.x); + EXPECT_EQ(1, mouse_wheel_1.event.y); + + // deltaX/Y, wheelTicksX/Y, and movementX/Y of the coalesced event are + // calculated properly. + EXPECT_EQ(mouse_wheel_1_copy.event.deltaX + mouse_wheel_0.event.deltaX, + mouse_wheel_1.event.deltaX); + EXPECT_EQ(mouse_wheel_1_copy.event.deltaY + mouse_wheel_0.event.deltaY, + mouse_wheel_1.event.deltaY); + EXPECT_EQ( + mouse_wheel_1_copy.event.wheelTicksX + mouse_wheel_0.event.wheelTicksX, + mouse_wheel_1.event.wheelTicksX); + EXPECT_EQ( + mouse_wheel_1_copy.event.wheelTicksY + mouse_wheel_0.event.wheelTicksY, + mouse_wheel_1.event.wheelTicksY); + EXPECT_EQ(mouse_wheel_1_copy.event.movementX + mouse_wheel_0.event.movementX, + mouse_wheel_1.event.movementX); + EXPECT_EQ(mouse_wheel_1_copy.event.movementY + mouse_wheel_0.event.movementY, + mouse_wheel_1.event.movementY); +} + +// Coalescing preserves the newer timestamp. +TEST_F(EventWithLatencyInfoTest, TimestampCoalescing) { + MouseWheelEventWithLatencyInfo mouse_wheel_0 = CreateMouseWheel(1, 1); + mouse_wheel_0.event.timeStampSeconds = 5.0; + MouseWheelEventWithLatencyInfo mouse_wheel_1 = CreateMouseWheel(2, 2); + mouse_wheel_1.event.timeStampSeconds = 10.0; + + EXPECT_TRUE(CanCoalesce(mouse_wheel_0, mouse_wheel_1)); + Coalesce(mouse_wheel_1, &mouse_wheel_0); + EXPECT_EQ(10.0, mouse_wheel_0.event.timeStampSeconds); +} + } // namespace } // namespace content diff --git a/chromium/content/common/input/gesture_event_stream_validator.cc b/chromium/content/common/input/gesture_event_stream_validator.cc index 9bdea8a481f..ef808246faf 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 "content/common/input/web_input_event_traits.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/web_input_event_traits.h" using blink::WebInputEvent; @@ -25,8 +25,8 @@ bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event, DCHECK(error_msg); error_msg->clear(); if (!WebInputEvent::isGestureEventType(event.type)) { - error_msg->append(base::StringPrintf( - "Invalid gesture type: %s", WebInputEventTraits::GetName(event.type))); + error_msg->append(base::StringPrintf("Invalid gesture type: %s", + WebInputEvent::GetName(event.type))); } switch (event.type) { case WebInputEvent::GestureScrollBegin: diff --git a/chromium/content/common/input/input_event.cc b/chromium/content/common/input/input_event.cc index ab20010ff3d..4991f85edbb 100644 --- a/chromium/content/common/input/input_event.cc +++ b/chromium/content/common/input/input_event.cc @@ -4,7 +4,7 @@ #include "content/common/input/input_event.h" -#include "content/common/input/web_input_event_traits.h" +#include "ui/events/blink/web_input_event_traits.h" namespace content { @@ -12,7 +12,7 @@ InputEvent::InputEvent() {} InputEvent::InputEvent(const blink::WebInputEvent& web_event, const ui::LatencyInfo& latency_info) - : web_event(WebInputEventTraits::Clone(web_event)), + : web_event(ui::WebInputEventTraits::Clone(web_event)), latency_info(latency_info) {} InputEvent::~InputEvent() {} diff --git a/chromium/content/common/input/input_event.h b/chromium/content/common/input/input_event.h index 58485e13216..6cc7c7fefbe 100644 --- a/chromium/content/common/input/input_event.h +++ b/chromium/content/common/input/input_event.h @@ -9,7 +9,7 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "content/common/input/scoped_web_input_event.h" +#include "ui/events/blink/scoped_web_input_event.h" #include "ui/events/latency_info.h" namespace blink { @@ -26,7 +26,7 @@ class CONTENT_EXPORT InputEvent { const ui::LatencyInfo& latency_info); ~InputEvent(); - ScopedWebInputEvent web_event; + ui::ScopedWebInputEvent web_event; ui::LatencyInfo latency_info; private: diff --git a/chromium/content/common/input/input_event_ack.cc b/chromium/content/common/input/input_event_ack.cc index 689eda6ad55..c7af9f85d25 100644 --- a/chromium/content/common/input/input_event_ack.cc +++ b/chromium/content/common/input/input_event_ack.cc @@ -12,7 +12,7 @@ InputEventAck::InputEventAck( blink::WebInputEvent::Type type, InputEventAckState state, const ui::LatencyInfo& latency, - std::unique_ptr<content::DidOverscrollParams> overscroll, + std::unique_ptr<ui::DidOverscrollParams> overscroll, uint32_t unique_touch_event_id) : type(type), state(state), diff --git a/chromium/content/common/input/input_event_ack.h b/chromium/content/common/input/input_event_ack.h index 565b66f6461..66b003d4a5f 100644 --- a/chromium/content/common/input/input_event_ack.h +++ b/chromium/content/common/input/input_event_ack.h @@ -10,9 +10,9 @@ #include <memory> #include "content/common/content_export.h" -#include "content/common/input/did_overscroll_params.h" #include "content/common/input/input_event_ack_state.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/did_overscroll_params.h" #include "ui/events/latency_info.h" namespace content { @@ -22,7 +22,7 @@ struct CONTENT_EXPORT InputEventAck { InputEventAck(blink::WebInputEvent::Type type, InputEventAckState state, const ui::LatencyInfo& latency, - std::unique_ptr<content::DidOverscrollParams> overscroll, + std::unique_ptr<ui::DidOverscrollParams> overscroll, uint32_t unique_touch_event_id); InputEventAck(blink::WebInputEvent::Type type, InputEventAckState state, @@ -38,7 +38,7 @@ struct CONTENT_EXPORT InputEventAck { blink::WebInputEvent::Type type; InputEventAckState state; ui::LatencyInfo latency; - std::unique_ptr<content::DidOverscrollParams> overscroll; + std::unique_ptr<ui::DidOverscrollParams> overscroll; uint32_t unique_touch_event_id; }; diff --git a/chromium/content/common/input/input_event_dispatch_type.h b/chromium/content/common/input/input_event_dispatch_type.h index ea802ff2c81..5f3234c3038 100644 --- a/chromium/content/common/input/input_event_dispatch_type.h +++ b/chromium/content/common/input/input_event_dispatch_type.h @@ -15,10 +15,7 @@ enum InputEventDispatchType { DISPATCH_TYPE_BLOCKING_NOTIFY_MAIN, // Dispatch a non-blocking event. Sender will not receive an ACK. DISPATCH_TYPE_NON_BLOCKING, - // Dispatch a non-blocking event and notify main thread as well. This type - // should only be sent from the compositor to main thread. - DISPATCH_TYPE_NON_BLOCKING_NOTIFY_MAIN, - DISPATCH_TYPE_MAX = DISPATCH_TYPE_NON_BLOCKING_NOTIFY_MAIN + DISPATCH_TYPE_MAX = DISPATCH_TYPE_NON_BLOCKING }; } // namespace content diff --git a/chromium/content/common/input/input_event_stream_validator.cc b/chromium/content/common/input/input_event_stream_validator.cc index f8a39994b45..1a1ffd36184 100644 --- a/chromium/content/common/input/input_event_stream_validator.cc +++ b/chromium/content/common/input/input_event_stream_validator.cc @@ -6,9 +6,9 @@ #include "base/command_line.h" #include "base/logging.h" -#include "content/common/input/web_input_event_traits.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/web_input_event_traits.h" using blink::WebInputEvent; using blink::WebGestureEvent; @@ -30,7 +30,7 @@ void InputEventStreamValidator::Validate(const WebInputEvent& event) { DCHECK(ValidateImpl(event, &error_msg_)) << error_msg_ - << "\nInvalid Event: " << WebInputEventTraits::ToString(event); + << "\nInvalid Event: " << ui::WebInputEventTraits::ToString(event); } bool InputEventStreamValidator::ValidateImpl(const blink::WebInputEvent& event, diff --git a/chromium/content/common/input/input_param_traits.cc b/chromium/content/common/input/input_param_traits.cc index 72810bfb0c4..0fc7a56f56a 100644 --- a/chromium/content/common/input/input_param_traits.cc +++ b/chromium/content/common/input/input_param_traits.cc @@ -11,8 +11,8 @@ #include "content/common/input/synthetic_pointer_action_params.h" #include "content/common/input/synthetic_smooth_drag_gesture_params.h" #include "content/common/input/synthetic_smooth_scroll_gesture_params.h" -#include "content/common/input/web_input_event_traits.h" #include "content/common/input_messages.h" +#include "ui/events/blink/web_input_event_traits.h" namespace IPC { namespace { @@ -28,7 +28,7 @@ std::unique_ptr<content::SyntheticGestureParams> ReadGestureParams( } } // namespace -void ParamTraits<content::ScopedWebInputEvent>::GetSize(base::PickleSizer* s, +void ParamTraits<ui::ScopedWebInputEvent>::GetSize(base::PickleSizer* s, const param_type& p) { bool valid_web_event = !!p; GetParamSize(s, valid_web_event); @@ -36,7 +36,7 @@ void ParamTraits<content::ScopedWebInputEvent>::GetSize(base::PickleSizer* s, GetParamSize(s, static_cast<WebInputEventPointer>(p.get())); } -void ParamTraits<content::ScopedWebInputEvent>::Write(base::Pickle* m, +void ParamTraits<ui::ScopedWebInputEvent>::Write(base::Pickle* m, const param_type& p) { bool valid_web_event = !!p; WriteParam(m, valid_web_event); @@ -44,7 +44,7 @@ void ParamTraits<content::ScopedWebInputEvent>::Write(base::Pickle* m, WriteParam(m, static_cast<WebInputEventPointer>(p.get())); } -bool ParamTraits<content::ScopedWebInputEvent>::Read(const base::Pickle* m, +bool ParamTraits<ui::ScopedWebInputEvent>::Read(const base::Pickle* m, base::PickleIterator* iter, param_type* p) { bool valid_web_event = false; @@ -55,11 +55,11 @@ bool ParamTraits<content::ScopedWebInputEvent>::Read(const base::Pickle* m, !web_event_pointer) return false; - (*p) = content::WebInputEventTraits::Clone(*web_event_pointer); + (*p) = ui::WebInputEventTraits::Clone(*web_event_pointer); return true; } -void ParamTraits<content::ScopedWebInputEvent>::Log(const param_type& p, +void ParamTraits<ui::ScopedWebInputEvent>::Log(const param_type& p, std::string* l) { LogParam(static_cast<WebInputEventPointer>(p.get()), l); } diff --git a/chromium/content/common/input/input_param_traits.h b/chromium/content/common/input/input_param_traits.h index dc901196acb..ba20f96e485 100644 --- a/chromium/content/common/input/input_param_traits.h +++ b/chromium/content/common/input/input_param_traits.h @@ -10,14 +10,14 @@ #include "content/common/content_export.h" #include "content/common/content_param_traits_macros.h" -#include "content/common/input/scoped_web_input_event.h" #include "content/common/input/synthetic_gesture_packet.h" +#include "ui/events/blink/scoped_web_input_event.h" namespace IPC { template <> -struct CONTENT_EXPORT ParamTraits<content::ScopedWebInputEvent> { - typedef content::ScopedWebInputEvent param_type; +struct CONTENT_EXPORT ParamTraits<ui::ScopedWebInputEvent> { + typedef ui::ScopedWebInputEvent param_type; static void GetSize(base::PickleSizer* s, const param_type& p); static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, diff --git a/chromium/content/common/input/input_param_traits_unittest.cc b/chromium/content/common/input/input_param_traits_unittest.cc index 07a7ac3bfd7..01acafc2772 100644 --- a/chromium/content/common/input/input_param_traits_unittest.cc +++ b/chromium/content/common/input/input_param_traits_unittest.cc @@ -7,6 +7,7 @@ #include <stddef.h> #include <utility> +#include "base/memory/ptr_util.h" #include "content/common/input/input_event.h" #include "content/common/input/synthetic_gesture_params.h" #include "content/common/input/synthetic_pinch_gesture_params.h" @@ -89,7 +90,9 @@ class InputParamTraitsTest : public testing::Test { EXPECT_EQ(a->position(), b->position()); } if (a->pointer_action_type() != - SyntheticPointerActionParams::PointerActionType::PROCESS) { + SyntheticPointerActionParams::PointerActionType::PROCESS && + a->pointer_action_type() != + SyntheticPointerActionParams::PointerActionType::FINISH) { EXPECT_EQ(a->index(), b->index()); } } @@ -272,9 +275,9 @@ TEST_F(InputParamTraitsTest, SyntheticTapGestureParams) { } TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsMove) { - std::unique_ptr<SyntheticPointerActionParams> gesture_params( - new SyntheticPointerActionParams( - SyntheticPointerActionParams::PointerActionType::MOVE)); + std::unique_ptr<SyntheticPointerActionParams> gesture_params = + base::MakeUnique<SyntheticPointerActionParams>( + SyntheticPointerActionParams::PointerActionType::MOVE); gesture_params->gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; gesture_params->set_position(gfx::PointF(356, 287)); gesture_params->set_index(0); @@ -286,9 +289,9 @@ TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsMove) { } TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsRelease) { - std::unique_ptr<SyntheticPointerActionParams> gesture_params( - new SyntheticPointerActionParams( - SyntheticPointerActionParams::PointerActionType::RELEASE)); + std::unique_ptr<SyntheticPointerActionParams> gesture_params = + base::MakeUnique<SyntheticPointerActionParams>( + SyntheticPointerActionParams::PointerActionType::RELEASE); gesture_params->gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; gesture_params->set_index(0); ASSERT_EQ(SyntheticGestureParams::POINTER_ACTION, @@ -299,9 +302,21 @@ TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsRelease) { } TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsProcess) { - std::unique_ptr<SyntheticPointerActionParams> gesture_params( - new SyntheticPointerActionParams( - SyntheticPointerActionParams::PointerActionType::PROCESS)); + std::unique_ptr<SyntheticPointerActionParams> gesture_params = + base::MakeUnique<SyntheticPointerActionParams>( + SyntheticPointerActionParams::PointerActionType::PROCESS); + gesture_params->gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; + ASSERT_EQ(SyntheticGestureParams::POINTER_ACTION, + gesture_params->GetGestureType()); + SyntheticGesturePacket packet_in; + packet_in.set_gesture_params(std::move(gesture_params)); + Verify(packet_in); +} + +TEST_F(InputParamTraitsTest, SyntheticPointerActionParamsFinish) { + std::unique_ptr<SyntheticPointerActionParams> gesture_params = + base::MakeUnique<SyntheticPointerActionParams>( + SyntheticPointerActionParams::PointerActionType::FINISH); gesture_params->gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; ASSERT_EQ(SyntheticGestureParams::POINTER_ACTION, gesture_params->GetGestureType()); diff --git a/chromium/content/common/input/scoped_web_input_event.cc b/chromium/content/common/input/scoped_web_input_event.cc deleted file mode 100644 index 8cd6e8a3862..00000000000 --- a/chromium/content/common/input/scoped_web_input_event.cc +++ /dev/null @@ -1,26 +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/common/input/scoped_web_input_event.h" - -#include "base/logging.h" -#include "content/common/input/web_input_event_traits.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" - -using blink::WebGestureEvent; -using blink::WebInputEvent; -using blink::WebKeyboardEvent; -using blink::WebMouseEvent; -using blink::WebMouseWheelEvent; -using blink::WebTouchEvent; - -namespace content { - -WebInputEventDeleter::WebInputEventDeleter() {} - -void WebInputEventDeleter::operator()(WebInputEvent* web_event) const { - WebInputEventTraits::Delete(web_event); -} - -} // namespace content diff --git a/chromium/content/common/input/scoped_web_input_event.h b/chromium/content/common/input/scoped_web_input_event.h deleted file mode 100644 index bc502eef6a7..00000000000 --- a/chromium/content/common/input/scoped_web_input_event.h +++ /dev/null @@ -1,28 +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_COMMON_INPUT_SCOPED_WEB_INPUT_EVENT_H_ -#define CONTENT_COMMON_INPUT_SCOPED_WEB_INPUT_EVENT_H_ - -#include <memory> - -#include "content/common/content_export.h" - -namespace blink { -class WebInputEvent; -} - -namespace content { - -// blink::WebInputEvent does not provide a virtual destructor. -struct CONTENT_EXPORT WebInputEventDeleter { - WebInputEventDeleter(); - void operator()(blink::WebInputEvent* web_event) const; -}; -typedef std::unique_ptr<blink::WebInputEvent, WebInputEventDeleter> - ScopedWebInputEvent; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_SCOPED_WEB_INPUT_EVENT_H_ diff --git a/chromium/content/common/input/synthetic_pointer_action_params.h b/chromium/content/common/input/synthetic_pointer_action_params.h index fe6c9f9b4a3..4e51f036b73 100644 --- a/chromium/content/common/input/synthetic_pointer_action_params.h +++ b/chromium/content/common/input/synthetic_pointer_action_params.h @@ -22,14 +22,16 @@ struct CONTENT_EXPORT SyntheticPointerActionParams : public SyntheticGestureParams { public: // Actions are queued up until we receive a PROCESS action, at which point - // we'll dispatch all queued events. + // we'll dispatch all queued events. A FINISH action will be received when + // we reach the end of the action sequence. enum class PointerActionType { NOT_INITIALIZED, PRESS, MOVE, RELEASE, PROCESS, - POINTER_ACTION_TYPE_MAX = PROCESS + FINISH, + POINTER_ACTION_TYPE_MAX = FINISH }; SyntheticPointerActionParams(); @@ -47,7 +49,10 @@ struct CONTENT_EXPORT SyntheticPointerActionParams } void set_index(int index) { - DCHECK(pointer_action_type_ != PointerActionType::PROCESS); + DCHECK(pointer_action_type_ != PointerActionType::PROCESS && + pointer_action_type_ != PointerActionType::FINISH); + // For all mouse pointer actions, the index should always be 0. + DCHECK(gesture_source_type != MOUSE_INPUT || index == 0); index_ = index; } @@ -60,7 +65,9 @@ struct CONTENT_EXPORT SyntheticPointerActionParams PointerActionType pointer_action_type() const { return pointer_action_type_; } int index() const { - DCHECK(pointer_action_type_ != PointerActionType::PROCESS); + DCHECK(pointer_action_type_ != PointerActionType::PROCESS && + pointer_action_type_ != PointerActionType::FINISH); + DCHECK(gesture_source_type != MOUSE_INPUT || index_ == 0); return index_; } 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 c5962b9a74e..d6705611ad1 100644 --- a/chromium/content/common/input/synthetic_web_input_event_builders.cc +++ b/chromium/content/common/input/synthetic_web_input_event_builders.cc @@ -40,9 +40,9 @@ WebMouseEvent SyntheticWebMouseEventBuilder::Build( result.modifiers = modifiers; if (type == WebInputEvent::MouseDown || type == WebInputEvent::MouseUp) - result.button = WebMouseEvent::ButtonLeft; + result.button = WebMouseEvent::Button::Left; else - result.button = WebMouseEvent::ButtonNone; + result.button = WebMouseEvent::Button::NoButton; return result; } @@ -189,7 +189,7 @@ void SyntheticWebTouchEvent::ResetPoints() { } int SyntheticWebTouchEvent::PressPoint(float x, float y) { - if (touchesLength == touchesLengthCap) + if (touchesLength == kTouchesLengthCap) return -1; WebTouchPoint& point = touches[touchesLength]; point.id = touchesLength; @@ -208,7 +208,7 @@ int SyntheticWebTouchEvent::PressPoint(float x, float y) { void SyntheticWebTouchEvent::MovePoint(int index, float x, float y) { CHECK_GE(index, 0); - CHECK_LT(index, touchesLengthCap); + CHECK_LT(index, kTouchesLengthCap); // Always set this bit to avoid otherwise unexpected touchmove suppression. // The caller can opt-out explicitly, if necessary. movedBeyondSlopRegion = true; @@ -222,7 +222,7 @@ void SyntheticWebTouchEvent::MovePoint(int index, float x, float y) { void SyntheticWebTouchEvent::ReleasePoint(int index) { CHECK_GE(index, 0); - CHECK_LT(index, touchesLengthCap); + CHECK_LT(index, kTouchesLengthCap); touches[index].state = WebTouchPoint::StateReleased; WebTouchEventTraits::ResetType( WebInputEvent::TouchEnd, timeStampSeconds, this); @@ -230,7 +230,7 @@ void SyntheticWebTouchEvent::ReleasePoint(int index) { void SyntheticWebTouchEvent::CancelPoint(int index) { CHECK_GE(index, 0); - CHECK_LT(index, touchesLengthCap); + CHECK_LT(index, kTouchesLengthCap); touches[index].state = WebTouchPoint::StateCancelled; WebTouchEventTraits::ResetType( WebInputEvent::TouchCancel, timeStampSeconds, this); diff --git a/chromium/content/common/input/touch_event_stream_validator.cc b/chromium/content/common/input/touch_event_stream_validator.cc index 23675b9f1bf..870f196e49f 100644 --- a/chromium/content/common/input/touch_event_stream_validator.cc +++ b/chromium/content/common/input/touch_event_stream_validator.cc @@ -6,8 +6,8 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" -#include "content/common/input/web_input_event_traits.h" #include "content/common/input/web_touch_event_traits.h" +#include "ui/events/blink/web_input_event_traits.h" using base::StringPrintf; using blink::WebInputEvent; @@ -62,7 +62,7 @@ bool TouchEventStreamValidator::Validate(const WebTouchEvent& event, if (!WebInputEvent::isTouchEventType(event.type)) { error_msg->append(StringPrintf("Touch event has invalid type: %s\n", - WebInputEventTraits::GetName(event.type))); + WebInputEvent::GetName(event.type))); } // Allow "hard" restarting of touch stream validation. This is necessary @@ -160,7 +160,7 @@ bool TouchEventStreamValidator::Validate(const WebTouchEvent& event, if (!found_valid_state_for_type) { error_msg->append( StringPrintf("No valid touch point corresponding to event type: %s\n", - WebInputEventTraits::GetName(event.type))); + WebInputEvent::GetName(event.type))); } return error_msg->empty(); diff --git a/chromium/content/common/input/web_input_event_queue.h b/chromium/content/common/input/web_input_event_queue.h index eab05997a37..59a4d9a9c42 100644 --- a/chromium/content/common/input/web_input_event_queue.h +++ b/chromium/content/common/input/web_input_event_queue.h @@ -10,44 +10,35 @@ namespace content { -enum class WebInputEventQueueState { ITEM_PENDING, ITEM_NOT_PENDING }; - -// WebInputEventQueue is a coalescing queue with the addition of a state -// variable that represents whether an item is pending to be processed. -// The desired usage sending with this queue is: -// if (queue.state() == WebInputEventQueueState::ITEM_PENDING) { -// queue.Queue(T); -// } else { -// send T -// queue.set_state(WebInputEventQueueState::ITEM_PENDING); -// } -// -// Processing the event response: -// if (!queue.empty()) { -// T = queue.Pop(); -// send T now -// } else { -// queue.set_state(WebInputEventQueueState::ITEM_NOT_PENDING); -// } -// +// WebInputEventQueue is a coalescing queue. It will examine +// the current events in the queue and will attempt to coalesce with +// the last event of the same class type. template <typename T> class WebInputEventQueue { public: - WebInputEventQueue() : state_(WebInputEventQueueState::ITEM_NOT_PENDING) {} + WebInputEventQueue() {} // Adds an event to the queue. The event may be coalesced with previously // queued events. - void Queue(const T& event) { - if (!queue_.empty()) { - std::unique_ptr<T>& last_event = queue_.back(); - if (last_event->CanCoalesceWith(event)) { - last_event->CoalesceWith(event); + void Queue(std::unique_ptr<T> event) { + for (auto last_event_iter = queue_.rbegin(); + last_event_iter != queue_.rend(); ++last_event_iter) { + if (!(*last_event_iter)->event().isSameEventClass(event->event())) { + continue; + } + + if ((*last_event_iter)->CanCoalesceWith(*event.get())) { + (*last_event_iter)->CoalesceWith(*event.get()); return; } + break; } - queue_.emplace_back(std::unique_ptr<T>(new T(event))); + queue_.emplace_back(std::move(event)); } + const std::unique_ptr<T>& front() const { return queue_.front(); } + const std::unique_ptr<T>& at(size_t pos) const { return queue_.at(pos); } + std::unique_ptr<T> Pop() { std::unique_ptr<T> result; if (!queue_.empty()) { @@ -61,14 +52,9 @@ class WebInputEventQueue { size_t size() const { return queue_.size(); } - void set_state(WebInputEventQueueState state) { state_ = state; } - - WebInputEventQueueState state() const WARN_UNUSED_RESULT { return state_; } - private: typedef std::deque<std::unique_ptr<T>> EventQueue; EventQueue queue_; - WebInputEventQueueState state_; DISALLOW_COPY_AND_ASSIGN(WebInputEventQueue); }; diff --git a/chromium/content/common/input/web_input_event_traits.cc b/chromium/content/common/input/web_input_event_traits.cc deleted file mode 100644 index fd2115021fc..00000000000 --- a/chromium/content/common/input/web_input_event_traits.cc +++ /dev/null @@ -1,539 +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/common/input/web_input_event_traits.h" - -#include <bitset> -#include <limits> - -#include "base/logging.h" -#include "base/strings/stringprintf.h" - -using base::StringAppendF; -using base::SStringPrintf; -using blink::WebGestureEvent; -using blink::WebInputEvent; -using blink::WebKeyboardEvent; -using blink::WebMouseEvent; -using blink::WebMouseWheelEvent; -using blink::WebTouchEvent; -using blink::WebTouchPoint; -using std::numeric_limits; - -namespace content { -namespace { - -const int kInvalidTouchIndex = -1; - -void ApppendEventDetails(const WebKeyboardEvent& event, std::string* result) { - StringAppendF(result, - "{\n WinCode: %d\n NativeCode: %d\n IsSystem: %d\n" - " Text: %s\n UnmodifiedText: %s\n KeyIdentifier: %s\n}", - event.windowsKeyCode, - event.nativeKeyCode, - event.isSystemKey, - reinterpret_cast<const char*>(event.text), - reinterpret_cast<const char*>(event.unmodifiedText), - reinterpret_cast<const char*>(event.keyIdentifier)); -} - -void ApppendEventDetails(const WebMouseEvent& event, std::string* result) { - StringAppendF(result, - "{\n Button: %d\n Pos: (%d, %d)\n WindowPos: (%d, %d)\n" - " GlobalPos: (%d, %d)\n Movement: (%d, %d)\n Clicks: %d\n}", - event.button, - event.x, - event.y, - event.windowX, - event.windowY, - event.globalX, - event.globalY, - event.movementX, - event.movementY, - event.clickCount); -} - -void ApppendEventDetails(const WebMouseWheelEvent& event, std::string* result) { - StringAppendF( - result, - "{\n Delta: (%f, %f)\n WheelTicks: (%f, %f)\n Accel: (%f, %f)\n" - " ScrollByPage: %d\n HasPreciseScrollingDeltas: %d\n" - " Phase: (%d, %d)\n CanRubberband: (%d, %d)\n}", - event.deltaX, event.deltaY, event.wheelTicksX, event.wheelTicksY, - event.accelerationRatioX, event.accelerationRatioY, event.scrollByPage, - event.hasPreciseScrollingDeltas, event.phase, event.momentumPhase, - event.canRubberbandLeft, event.canRubberbandRight); -} - -void ApppendEventDetails(const WebGestureEvent& event, std::string* result) { - StringAppendF(result, - "{\n Pos: (%d, %d)\n GlobalPos: (%d, %d)\n SourceDevice: %d\n" - " RawData: (%f, %f, %f, %f, %d)\n}", - event.x, - event.y, - event.globalX, - event.globalY, - event.sourceDevice, - event.data.scrollUpdate.deltaX, - event.data.scrollUpdate.deltaY, - event.data.scrollUpdate.velocityX, - event.data.scrollUpdate.velocityY, - event.data.scrollUpdate.previousUpdateInSequencePrevented); -} - -void ApppendTouchPointDetails(const WebTouchPoint& point, std::string* result) { - StringAppendF(result, - " (ID: %d, State: %d, ScreenPos: (%f, %f), Pos: (%f, %f)," - " Radius: (%f, %f), Rot: %f, Force: %f," - " Tilt: (%d, %d)),\n", - point.id, - point.state, - point.screenPosition.x, - point.screenPosition.y, - point.position.x, - point.position.y, - point.radiusX, - point.radiusY, - point.rotationAngle, - point.force, - point.tiltX, - point.tiltY); -} - -void ApppendEventDetails(const WebTouchEvent& event, std::string* result) { - StringAppendF(result, - "{\n Touches: %u, DispatchType: %d, CausesScrolling: %d," - " uniqueTouchEventId: %u\n[\n", - event.touchesLength, event.dispatchType, - event.movedBeyondSlopRegion, event.uniqueTouchEventId); - for (unsigned i = 0; i < event.touchesLength; ++i) - ApppendTouchPointDetails(event.touches[i], result); - result->append(" ]\n}"); -} - -bool CanCoalesce(const WebKeyboardEvent& event_to_coalesce, - const WebKeyboardEvent& event) { - return false; -} - -void Coalesce(const WebKeyboardEvent& event_to_coalesce, - WebKeyboardEvent* event) { - DCHECK(CanCoalesce(event_to_coalesce, *event)); -} - -bool CanCoalesce(const WebMouseEvent& event_to_coalesce, - const WebMouseEvent& event) { - return event.type == event_to_coalesce.type && - event.type == WebInputEvent::MouseMove; -} - -void Coalesce(const WebMouseEvent& event_to_coalesce, WebMouseEvent* event) { - DCHECK(CanCoalesce(event_to_coalesce, *event)); - // Accumulate movement deltas. - int x = event->movementX; - int y = event->movementY; - *event = event_to_coalesce; - event->movementX += x; - event->movementY += y; -} - -bool CanCoalesce(const WebMouseWheelEvent& event_to_coalesce, - const WebMouseWheelEvent& event) { - return event.modifiers == event_to_coalesce.modifiers && - event.scrollByPage == event_to_coalesce.scrollByPage && - event.phase == event_to_coalesce.phase && - event.momentumPhase == event_to_coalesce.momentumPhase && - event.hasPreciseScrollingDeltas == - event_to_coalesce.hasPreciseScrollingDeltas; -} - -float GetUnacceleratedDelta(float accelerated_delta, float acceleration_ratio) { - return accelerated_delta * acceleration_ratio; -} - -float GetAccelerationRatio(float accelerated_delta, float unaccelerated_delta) { - if (unaccelerated_delta == 0.f || accelerated_delta == 0.f) - return 1.f; - return unaccelerated_delta / accelerated_delta; -} - -void Coalesce(const WebMouseWheelEvent& event_to_coalesce, - WebMouseWheelEvent* event) { - DCHECK(CanCoalesce(event_to_coalesce, *event)); - float unaccelerated_x = - GetUnacceleratedDelta(event->deltaX, - event->accelerationRatioX) + - GetUnacceleratedDelta(event_to_coalesce.deltaX, - event_to_coalesce.accelerationRatioX); - float unaccelerated_y = - GetUnacceleratedDelta(event->deltaY, - event->accelerationRatioY) + - GetUnacceleratedDelta(event_to_coalesce.deltaY, - event_to_coalesce.accelerationRatioY); - event->deltaX += event_to_coalesce.deltaX; - event->deltaY += event_to_coalesce.deltaY; - event->wheelTicksX += event_to_coalesce.wheelTicksX; - event->wheelTicksY += event_to_coalesce.wheelTicksY; - event->accelerationRatioX = - GetAccelerationRatio(event->deltaX, unaccelerated_x); - event->accelerationRatioY = - GetAccelerationRatio(event->deltaY, unaccelerated_y); -} - -// Returns |kInvalidTouchIndex| iff |event| lacks a touch with an ID of |id|. -int GetIndexOfTouchID(const WebTouchEvent& event, int id) { - for (unsigned i = 0; i < event.touchesLength; ++i) { - if (event.touches[i].id == id) - return i; - } - return kInvalidTouchIndex; -} - -WebInputEvent::DispatchType MergeDispatchTypes( - WebInputEvent::DispatchType type_1, - WebInputEvent::DispatchType type_2) { - static_assert(WebInputEvent::DispatchType::Blocking < - WebInputEvent::DispatchType::EventNonBlocking, - "Enum not ordered correctly"); - static_assert(WebInputEvent::DispatchType::EventNonBlocking < - WebInputEvent::DispatchType::ListenersNonBlockingPassive, - "Enum not ordered correctly"); - static_assert( - WebInputEvent::DispatchType::ListenersNonBlockingPassive < - WebInputEvent::DispatchType::ListenersForcedNonBlockingPassive, - "Enum not ordered correctly"); - return static_cast<WebInputEvent::DispatchType>( - std::min(static_cast<int>(type_1), static_cast<int>(type_2))); -} - -bool CanCoalesce(const WebTouchEvent& event_to_coalesce, - const WebTouchEvent& event) { - if (event.type != event_to_coalesce.type || - event.type != WebInputEvent::TouchMove || - event.modifiers != event_to_coalesce.modifiers || - event.touchesLength != event_to_coalesce.touchesLength || - event.touchesLength > WebTouchEvent::touchesLengthCap) - return false; - - static_assert(WebTouchEvent::touchesLengthCap <= sizeof(int32_t) * 8U, - "suboptimal touchesLengthCap size"); - // Ensure that we have a 1-to-1 mapping of pointer ids between touches. - std::bitset<WebTouchEvent::touchesLengthCap> unmatched_event_touches( - (1 << event.touchesLength) - 1); - for (unsigned i = 0; i < event_to_coalesce.touchesLength; ++i) { - int event_touch_index = - GetIndexOfTouchID(event, event_to_coalesce.touches[i].id); - if (event_touch_index == kInvalidTouchIndex) - return false; - if (!unmatched_event_touches[event_touch_index]) - return false; - unmatched_event_touches[event_touch_index] = false; - } - return unmatched_event_touches.none(); -} - -void Coalesce(const WebTouchEvent& event_to_coalesce, WebTouchEvent* event) { - DCHECK(CanCoalesce(event_to_coalesce, *event)); - // The WebTouchPoints include absolute position information. So it is - // sufficient to simply replace the previous event with the new event-> - // However, it is necessary to make sure that all the points have the - // correct state, i.e. the touch-points that moved in the last event, but - // didn't change in the current event, will have Stationary state. It is - // necessary to change them back to Moved state. - WebTouchEvent old_event = *event; - *event = event_to_coalesce; - for (unsigned i = 0; i < event->touchesLength; ++i) { - int i_old = GetIndexOfTouchID(old_event, event->touches[i].id); - if (old_event.touches[i_old].state == blink::WebTouchPoint::StateMoved) - event->touches[i].state = blink::WebTouchPoint::StateMoved; - } - event->movedBeyondSlopRegion |= old_event.movedBeyondSlopRegion; - event->dispatchType = MergeDispatchTypes(old_event.dispatchType, - event_to_coalesce.dispatchType); -} - -bool CanCoalesce(const WebGestureEvent& event_to_coalesce, - const WebGestureEvent& event) { - if (event.type != event_to_coalesce.type || - event.sourceDevice != event_to_coalesce.sourceDevice || - event.modifiers != event_to_coalesce.modifiers) - return false; - - if (event.type == WebInputEvent::GestureScrollUpdate) - return true; - - // GesturePinchUpdate scales can be combined only if they share a focal point, - // e.g., with double-tap drag zoom. - if (event.type == WebInputEvent::GesturePinchUpdate && - event.x == event_to_coalesce.x && - event.y == event_to_coalesce.y) - return true; - - return false; -} - -void Coalesce(const WebGestureEvent& event_to_coalesce, - WebGestureEvent* event) { - DCHECK(CanCoalesce(event_to_coalesce, *event)); - if (event->type == WebInputEvent::GestureScrollUpdate) { - event->data.scrollUpdate.deltaX += - event_to_coalesce.data.scrollUpdate.deltaX; - event->data.scrollUpdate.deltaY += - event_to_coalesce.data.scrollUpdate.deltaY; - DCHECK_EQ( - event->data.scrollUpdate.previousUpdateInSequencePrevented, - event_to_coalesce.data.scrollUpdate.previousUpdateInSequencePrevented); - } else if (event->type == WebInputEvent::GesturePinchUpdate) { - event->data.pinchUpdate.scale *= event_to_coalesce.data.pinchUpdate.scale; - // Ensure the scale remains bounded above 0 and below Infinity so that - // we can reliably perform operations like log on the values. - if (event->data.pinchUpdate.scale < numeric_limits<float>::min()) - event->data.pinchUpdate.scale = numeric_limits<float>::min(); - else if (event->data.pinchUpdate.scale > numeric_limits<float>::max()) - event->data.pinchUpdate.scale = numeric_limits<float>::max(); - } -} - -struct WebInputEventToString { - template <class EventType> - bool Execute(const WebInputEvent& event, std::string* result) const { - SStringPrintf(result, "%s (Time: %lf, Modifiers: %d)\n", - WebInputEventTraits::GetName(event.type), - event.timeStampSeconds, - event.modifiers); - const EventType& typed_event = static_cast<const EventType&>(event); - ApppendEventDetails(typed_event, result); - return true; - } -}; - -struct WebInputEventSize { - template <class EventType> - bool Execute(WebInputEvent::Type /* type */, size_t* type_size) const { - *type_size = sizeof(EventType); - return true; - } -}; - -struct WebInputEventClone { - template <class EventType> - bool Execute(const WebInputEvent& event, - ScopedWebInputEvent* scoped_event) const { - DCHECK_EQ(sizeof(EventType), event.size); - *scoped_event = ScopedWebInputEvent( - new EventType(static_cast<const EventType&>(event))); - return true; - } -}; - -struct WebInputEventDelete { - template <class EventType> - bool Execute(WebInputEvent* event, bool* /* dummy_var */) const { - if (!event) - return false; - DCHECK_EQ(sizeof(EventType), event->size); - delete static_cast<EventType*>(event); - return true; - } -}; - -struct WebInputEventCanCoalesce { - template <class EventType> - bool Execute(const WebInputEvent& event_to_coalesce, - const WebInputEvent* event) const { - if (event_to_coalesce.type != event->type) - return false; - DCHECK_EQ(sizeof(EventType), event->size); - DCHECK_EQ(sizeof(EventType), event_to_coalesce.size); - return CanCoalesce(static_cast<const EventType&>(event_to_coalesce), - *static_cast<const EventType*>(event)); - } -}; - -struct WebInputEventCoalesce { - template <class EventType> - bool Execute(const WebInputEvent& event_to_coalesce, - WebInputEvent* event) const { - // New events get coalesced into older events, and the newer timestamp - // should always be preserved. - const double time_stamp_seconds = event_to_coalesce.timeStampSeconds; - Coalesce(static_cast<const EventType&>(event_to_coalesce), - static_cast<EventType*>(event)); - event->timeStampSeconds = time_stamp_seconds; - return true; - } -}; - -template <typename Operator, typename ArgIn, typename ArgOut> -bool Apply(Operator op, - WebInputEvent::Type type, - const ArgIn& arg_in, - ArgOut* arg_out) { - if (WebInputEvent::isMouseEventType(type)) - return op.template Execute<WebMouseEvent>(arg_in, arg_out); - else if (type == WebInputEvent::MouseWheel) - return op.template Execute<WebMouseWheelEvent>(arg_in, arg_out); - else if (WebInputEvent::isKeyboardEventType(type)) - return op.template Execute<WebKeyboardEvent>(arg_in, arg_out); - else if (WebInputEvent::isTouchEventType(type)) - return op.template Execute<WebTouchEvent>(arg_in, arg_out); - else if (WebInputEvent::isGestureEventType(type)) - return op.template Execute<WebGestureEvent>(arg_in, arg_out); - - NOTREACHED() << "Unknown webkit event type " << type; - return false; -} - -} // namespace - -const char* WebInputEventTraits::GetName(WebInputEvent::Type type) { -#define CASE_TYPE(t) case WebInputEvent::t: return #t - switch(type) { - CASE_TYPE(Undefined); - CASE_TYPE(MouseDown); - CASE_TYPE(MouseUp); - CASE_TYPE(MouseMove); - CASE_TYPE(MouseEnter); - CASE_TYPE(MouseLeave); - CASE_TYPE(ContextMenu); - CASE_TYPE(MouseWheel); - CASE_TYPE(RawKeyDown); - CASE_TYPE(KeyDown); - CASE_TYPE(KeyUp); - CASE_TYPE(Char); - CASE_TYPE(GestureScrollBegin); - CASE_TYPE(GestureScrollEnd); - CASE_TYPE(GestureScrollUpdate); - CASE_TYPE(GestureFlingStart); - CASE_TYPE(GestureFlingCancel); - CASE_TYPE(GestureShowPress); - CASE_TYPE(GestureTap); - CASE_TYPE(GestureTapUnconfirmed); - CASE_TYPE(GestureTapDown); - CASE_TYPE(GestureTapCancel); - CASE_TYPE(GestureDoubleTap); - CASE_TYPE(GestureTwoFingerTap); - CASE_TYPE(GestureLongPress); - CASE_TYPE(GestureLongTap); - CASE_TYPE(GesturePinchBegin); - CASE_TYPE(GesturePinchEnd); - CASE_TYPE(GesturePinchUpdate); - CASE_TYPE(TouchStart); - CASE_TYPE(TouchMove); - CASE_TYPE(TouchEnd); - CASE_TYPE(TouchCancel); - CASE_TYPE(TouchScrollStarted); - default: - // Must include default to let blink::WebInputEvent add new event types - // before they're added here. - DLOG(WARNING) << - "Unhandled WebInputEvent type in WebInputEventTraits::GetName.\n"; - break; - } -#undef CASE_TYPE - return ""; -} - -std::string WebInputEventTraits::ToString(const WebInputEvent& event) { - std::string result; - Apply(WebInputEventToString(), event.type, event, &result); - return result; -} - -size_t WebInputEventTraits::GetSize(WebInputEvent::Type type) { - size_t size = 0; - Apply(WebInputEventSize(), type, type, &size); - return size; -} - -ScopedWebInputEvent WebInputEventTraits::Clone(const WebInputEvent& event) { - ScopedWebInputEvent scoped_event; - Apply(WebInputEventClone(), event.type, event, &scoped_event); - return scoped_event; -} - -void WebInputEventTraits::Delete(WebInputEvent* event) { - if (!event) - return; - bool dummy_var = false; - Apply(WebInputEventDelete(), event->type, event, &dummy_var); -} - -bool WebInputEventTraits::CanCoalesce(const WebInputEvent& event_to_coalesce, - const WebInputEvent& event) { - // Early out before casting. - if (event_to_coalesce.type != event.type) - return false; - return Apply(WebInputEventCanCoalesce(), - event.type, - event_to_coalesce, - &event); -} - -void WebInputEventTraits::Coalesce(const WebInputEvent& event_to_coalesce, - WebInputEvent* event) { - DCHECK(event); - Apply(WebInputEventCoalesce(), event->type, event_to_coalesce, event); -} - -bool WebInputEventTraits::ShouldBlockEventStream(const WebInputEvent& event) { - switch (event.type) { - case WebInputEvent::MouseDown: - case WebInputEvent::MouseUp: - case WebInputEvent::MouseEnter: - case WebInputEvent::MouseLeave: - case WebInputEvent::ContextMenu: - case WebInputEvent::GestureScrollBegin: - case WebInputEvent::GestureScrollEnd: - case WebInputEvent::GestureShowPress: - case WebInputEvent::GestureTapUnconfirmed: - case WebInputEvent::GestureTapDown: - case WebInputEvent::GestureTapCancel: - case WebInputEvent::GesturePinchBegin: - case WebInputEvent::GesturePinchEnd: - return false; - - // TouchCancel and TouchScrollStarted should always be non-blocking. - case WebInputEvent::TouchCancel: - case WebInputEvent::TouchScrollStarted: - DCHECK_NE(WebInputEvent::Blocking, - static_cast<const WebTouchEvent&>(event).dispatchType); - return false; - - // Touch start and touch end indicate whether they are non-blocking - // (aka uncancelable) on the event. - case WebInputEvent::TouchStart: - case WebInputEvent::TouchEnd: - return static_cast<const WebTouchEvent&>(event).dispatchType == - WebInputEvent::Blocking; - - // Touch move events may be non-blocking but are always explicitly - // acknowledge by the renderer so they block the event stream. - case WebInputEvent::TouchMove: - default: - return true; - } -} - -bool WebInputEventTraits::CanCauseScroll( - const blink::WebMouseWheelEvent& event) { -#if defined(USE_AURA) - // Scroll events generated from the mouse wheel when the control key is held - // don't trigger scrolling. Instead, they may cause zooming. - return event.hasPreciseScrollingDeltas || - (event.modifiers & blink::WebInputEvent::ControlKey) == 0; -#else - return true; -#endif -} - -uint32_t WebInputEventTraits::GetUniqueTouchEventId( - const WebInputEvent& event) { - if (WebInputEvent::isTouchEventType(event.type)) { - return static_cast<const WebTouchEvent&>(event).uniqueTouchEventId; - } - return 0U; -} - -} // namespace content diff --git a/chromium/content/common/input/web_input_event_traits.h b/chromium/content/common/input/web_input_event_traits.h deleted file mode 100644 index 31d22fe8164..00000000000 --- a/chromium/content/common/input/web_input_event_traits.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_INPUT_WEB_INPUT_EVENT_TRAITS_H_ -#define CONTENT_COMMON_INPUT_WEB_INPUT_EVENT_TRAITS_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <string> - -#include "content/common/input/scoped_web_input_event.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" - -namespace content { - -// Utility class for performing operations on and with WebInputEvents. -class CONTENT_EXPORT WebInputEventTraits { - public: - static const char* GetName(blink::WebInputEvent::Type type); - static std::string ToString(const blink::WebInputEvent& event); - static size_t GetSize(blink::WebInputEvent::Type type); - static ScopedWebInputEvent Clone(const blink::WebInputEvent& event); - static void Delete(blink::WebInputEvent* event); - static bool CanCoalesce(const blink::WebInputEvent& event_to_coalesce, - const blink::WebInputEvent& event); - static void Coalesce(const blink::WebInputEvent& event_to_coalesce, - blink::WebInputEvent* event); - static bool ShouldBlockEventStream(const blink::WebInputEvent& event); - - static bool CanCauseScroll(const blink::WebMouseWheelEvent& event); - - // Return uniqueTouchEventId for WebTouchEvent, otherwise return 0. - static uint32_t GetUniqueTouchEventId(const blink::WebInputEvent& event); -}; - -} // namespace content - -#endif // CONTENT_COMMON_INPUT_WEB_INPUT_EVENT_TRAITS_H_ diff --git a/chromium/content/common/input/web_input_event_traits_unittest.cc b/chromium/content/common/input/web_input_event_traits_unittest.cc deleted file mode 100644 index 7c773f4f45a..00000000000 --- a/chromium/content/common/input/web_input_event_traits_unittest.cc +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/input/web_input_event_traits.h" - -#include <limits> - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebInputEvent.h" - -using blink::WebGestureEvent; -using blink::WebInputEvent; -using blink::WebKeyboardEvent; -using blink::WebMouseEvent; -using blink::WebMouseWheelEvent; -using blink::WebTouchEvent; -using blink::WebTouchPoint; -using std::numeric_limits; - -namespace content { -namespace { - -class WebInputEventTraitsTest : public testing::Test { - protected: - static WebTouchPoint CreateTouchPoint(WebTouchPoint::State state, int id) { - WebTouchPoint touch; - touch.state = state; - touch.id = id; - return touch; - } - - static WebTouchEvent CreateTouch(WebInputEvent::Type type) { - return CreateTouch(type, 1); - } - - static WebTouchEvent CreateTouch(WebInputEvent::Type type, - unsigned touch_count) { - WebTouchEvent event; - event.touchesLength = touch_count; - event.type = type; - return event; - } - - static WebGestureEvent CreateGesture(WebInputEvent::Type type, - float x, - float y) { - WebGestureEvent event; - event.type = type; - event.x = x; - event.y = y; - return event; - } - - static WebMouseWheelEvent CreateMouseWheel(float deltaX, float deltaY) { - WebMouseWheelEvent event; - event.type = WebInputEvent::MouseWheel; - event.deltaX = deltaX; - event.deltaY = deltaY; - return event; - } -}; - -TEST_F(WebInputEventTraitsTest, TouchEventCoalescing) { - WebTouchEvent touch0 = CreateTouch(WebInputEvent::TouchStart); - WebTouchEvent touch1 = CreateTouch(WebInputEvent::TouchMove); - - // Non touch-moves won't coalesce. - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(touch0, touch0)); - - // Touches of different types won't coalesce. - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - - // Touch moves with idential touch lengths and touch ids should coalesce. - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(touch1, touch1)); - - // Touch moves with different touch ids should not coalesce. - touch0 = CreateTouch(WebInputEvent::TouchMove); - touch1 = CreateTouch(WebInputEvent::TouchMove); - touch0.touches[0].id = 7; - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - touch0 = CreateTouch(WebInputEvent::TouchMove, 2); - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.touches[0].id = 1; - touch1.touches[0].id = 0; - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - - // Touch moves with different touch lengths should not coalesce. - touch0 = CreateTouch(WebInputEvent::TouchMove, 1); - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - - // Touch moves with identical touch ids in different orders should coalesce. - touch0 = CreateTouch(WebInputEvent::TouchMove, 2); - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.touches[0] = touch1.touches[1] = - CreateTouchPoint(WebTouchPoint::StateMoved, 1); - touch0.touches[1] = touch1.touches[0] = - CreateTouchPoint(WebTouchPoint::StateMoved, 0); - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - - // Pointers with the same ID's should coalesce. - touch0 = CreateTouch(WebInputEvent::TouchMove, 2); - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.touches[0] = touch1.touches[1] = - CreateTouchPoint(WebTouchPoint::StateMoved, 1); - WebInputEventTraits::Coalesce(touch0, &touch1); - ASSERT_EQ(1, touch1.touches[0].id); - ASSERT_EQ(0, touch1.touches[1].id); - EXPECT_EQ(WebTouchPoint::StateUndefined, touch1.touches[1].state); - EXPECT_EQ(WebTouchPoint::StateMoved, touch1.touches[0].state); - - // Movement from now-stationary pointers should be preserved. - touch0 = touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.touches[0] = CreateTouchPoint(WebTouchPoint::StateMoved, 1); - touch1.touches[1] = CreateTouchPoint(WebTouchPoint::StateStationary, 1); - touch0.touches[1] = CreateTouchPoint(WebTouchPoint::StateStationary, 0); - touch1.touches[0] = CreateTouchPoint(WebTouchPoint::StateMoved, 0); - WebInputEventTraits::Coalesce(touch0, &touch1); - ASSERT_EQ(1, touch1.touches[0].id); - ASSERT_EQ(0, touch1.touches[1].id); - EXPECT_EQ(WebTouchPoint::StateMoved, touch1.touches[0].state); - EXPECT_EQ(WebTouchPoint::StateMoved, touch1.touches[1].state); - - // Touch moves with different dispatchTypes coalesce. - touch0 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.dispatchType = WebInputEvent::DispatchType::Blocking; - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch1.dispatchType = WebInputEvent::DispatchType::EventNonBlocking; - touch0.touches[0] = touch1.touches[1] = - CreateTouchPoint(WebTouchPoint::StateMoved, 1); - touch0.touches[1] = touch1.touches[0] = - CreateTouchPoint(WebTouchPoint::StateMoved, 0); - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - WebInputEventTraits::Coalesce(touch0, &touch1); - ASSERT_EQ(WebInputEvent::DispatchType::Blocking, touch1.dispatchType); - - touch0 = CreateTouch(WebInputEvent::TouchMove, 2); - touch0.dispatchType = - WebInputEvent::DispatchType::ListenersForcedNonBlockingPassive; - touch1 = CreateTouch(WebInputEvent::TouchMove, 2); - touch1.dispatchType = - WebInputEvent::DispatchType::ListenersNonBlockingPassive; - touch0.touches[0] = touch1.touches[1] = - CreateTouchPoint(WebTouchPoint::StateMoved, 1); - touch0.touches[1] = touch1.touches[0] = - CreateTouchPoint(WebTouchPoint::StateMoved, 0); - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(touch0, touch1)); - WebInputEventTraits::Coalesce(touch0, &touch1); - ASSERT_EQ(WebInputEvent::DispatchType::ListenersNonBlockingPassive, - touch1.dispatchType); -} - -TEST_F(WebInputEventTraitsTest, PinchEventCoalescing) { - WebGestureEvent pinch0 = - CreateGesture(WebInputEvent::GesturePinchBegin, 1, 1); - WebGestureEvent pinch1 = - CreateGesture(WebInputEvent::GesturePinchUpdate, 2, 2); - - // Only GesturePinchUpdate's coalesce. - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(pinch0, pinch0)); - - // Pinch gestures of different types should not coalesce. - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(pinch0, pinch1)); - - // Pinches with different focal points should not coalesce. - pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 2, 2); - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(pinch0, pinch1)); - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(pinch0, pinch0)); - - // Coalesced scales are multiplicative. - pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch0.data.pinchUpdate.scale = 2.f; - pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch1.data.pinchUpdate.scale = 3.f; - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(pinch0, pinch0)); - WebInputEventTraits::Coalesce(pinch0, &pinch1); - EXPECT_EQ(2.f * 3.f, pinch1.data.pinchUpdate.scale); - - // Scales have a minimum value and can never reach 0. - ASSERT_GT(numeric_limits<float>::min(), 0); - pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch0.data.pinchUpdate.scale = numeric_limits<float>::min() * 2.0f; - pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch1.data.pinchUpdate.scale = numeric_limits<float>::min() * 5.0f; - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(pinch0, pinch1)); - WebInputEventTraits::Coalesce(pinch0, &pinch1); - EXPECT_EQ(numeric_limits<float>::min(), pinch1.data.pinchUpdate.scale); - - // Scales have a maximum value and can never reach Infinity. - pinch0 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch0.data.pinchUpdate.scale = numeric_limits<float>::max() / 2.0f; - pinch1 = CreateGesture(WebInputEvent::GesturePinchUpdate, 1, 1); - pinch1.data.pinchUpdate.scale = 10.0f; - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(pinch0, pinch1)); - WebInputEventTraits::Coalesce(pinch0, &pinch1); - EXPECT_EQ(numeric_limits<float>::max(), pinch1.data.pinchUpdate.scale); -} - -TEST_F(WebInputEventTraitsTest, WebMouseWheelEventCoalescing) { - WebMouseWheelEvent mouse_wheel_0 = CreateMouseWheel(1, 1); - WebMouseWheelEvent mouse_wheel_1 = CreateMouseWheel(2, 2); - - // WebMouseWheelEvent objects with same values except different deltaX and - // deltaY should coalesce. - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(mouse_wheel_0, mouse_wheel_1)); - - // WebMouseWheelEvent objects with different modifiers should not coalesce. - mouse_wheel_0 = CreateMouseWheel(1, 1); - mouse_wheel_1 = CreateMouseWheel(1, 1); - mouse_wheel_0.modifiers = blink::WebInputEvent::ControlKey; - mouse_wheel_1.modifiers = blink::WebInputEvent::ShiftKey; - EXPECT_FALSE(WebInputEventTraits::CanCoalesce(mouse_wheel_0, mouse_wheel_1)); -} - -// Coalescing preserves the newer timestamp. -TEST_F(WebInputEventTraitsTest, TimestampCoalescing) { - WebMouseWheelEvent mouse_wheel_0 = CreateMouseWheel(1, 1); - mouse_wheel_0.timeStampSeconds = 5.0; - WebMouseWheelEvent mouse_wheel_1 = CreateMouseWheel(2, 2); - mouse_wheel_1.timeStampSeconds = 10.0; - - EXPECT_TRUE(WebInputEventTraits::CanCoalesce(mouse_wheel_0, mouse_wheel_1)); - WebInputEventTraits::Coalesce(mouse_wheel_1, &mouse_wheel_0); - EXPECT_EQ(10.0, mouse_wheel_0.timeStampSeconds); -} - -// Very basic smoke test to ensure stringification doesn't explode. -TEST_F(WebInputEventTraitsTest, ToString) { - WebKeyboardEvent key; - key.type = WebInputEvent::RawKeyDown; - EXPECT_FALSE(WebInputEventTraits::ToString(key).empty()); - - WebMouseEvent mouse; - mouse.type = WebInputEvent::MouseMove; - EXPECT_FALSE(WebInputEventTraits::ToString(mouse).empty()); - - WebMouseWheelEvent mouse_wheel; - mouse_wheel.type = WebInputEvent::MouseWheel; - EXPECT_FALSE(WebInputEventTraits::ToString(mouse_wheel).empty()); - - WebGestureEvent gesture = - CreateGesture(WebInputEvent::GesturePinchBegin, 1, 1); - EXPECT_FALSE(WebInputEventTraits::ToString(gesture).empty()); - - WebTouchEvent touch = CreateTouch(WebInputEvent::TouchStart); - EXPECT_FALSE(WebInputEventTraits::ToString(touch).empty()); -} - -} // namespace -} // namespace content diff --git a/chromium/content/common/input/web_touch_event_traits.h b/chromium/content/common/input/web_touch_event_traits.h index 33ac8c7f265..1f974aed43f 100644 --- a/chromium/content/common/input/web_touch_event_traits.h +++ b/chromium/content/common/input/web_touch_event_traits.h @@ -5,8 +5,9 @@ #ifndef CONTENT_COMMON_INPUT_WEB_TOUCH_EVENT_TRAITS_H_ #define CONTENT_COMMON_INPUT_WEB_TOUCH_EVENT_TRAITS_H_ -#include "content/common/input/scoped_web_input_event.h" +#include "content/common/content_export.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/scoped_web_input_event.h" namespace content { diff --git a/chromium/content/common/input_messages.h b/chromium/content/common/input_messages.h index 4d3c0ce4a63..4c68ae82eb3 100644 --- a/chromium/content/common/input_messages.h +++ b/chromium/content/common/input_messages.h @@ -11,7 +11,6 @@ #include "content/common/content_export.h" #include "content/common/content_param_traits.h" #include "content/common/edit_command.h" -#include "content/common/input/did_overscroll_params.h" #include "content/common/input/input_event.h" #include "content/common/input/input_event_ack.h" #include "content/common/input/input_event_ack_state.h" @@ -27,6 +26,7 @@ #include "content/common/input/touch_action.h" #include "ipc/ipc_message_macros.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/events/blink/did_overscroll_params.h" #include "ui/events/ipc/latency_info_param_traits.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" @@ -56,15 +56,9 @@ IPC_ENUM_TRAITS_MAX_VALUE( POINTER_ACTION_TYPE_MAX) IPC_ENUM_TRAITS_MAX_VALUE(content::InputEventDispatchType, content::InputEventDispatchType::DISPATCH_TYPE_MAX) -IPC_ENUM_TRAITS_VALIDATE(content::TouchAction, ( - value >= 0 && - value <= content::TOUCH_ACTION_MAX && - (!(value & content::TOUCH_ACTION_NONE) || - (value == content::TOUCH_ACTION_NONE)) && - (!(value & content::TOUCH_ACTION_PINCH_ZOOM) || - (value == content::TOUCH_ACTION_MANIPULATION)))) - -IPC_STRUCT_TRAITS_BEGIN(content::DidOverscrollParams) +IPC_ENUM_TRAITS_MAX_VALUE(content::TouchAction, content::TOUCH_ACTION_MAX) + +IPC_STRUCT_TRAITS_BEGIN(ui::DidOverscrollParams) IPC_STRUCT_TRAITS_MEMBER(accumulated_overscroll) IPC_STRUCT_TRAITS_MEMBER(latest_overscroll_delta) IPC_STRUCT_TRAITS_MEMBER(current_fling_velocity) @@ -166,11 +160,15 @@ IPC_MESSAGE_ROUTED5( int, /* selectiont_start */ int /* selection_end */) -// This message confirms an ongoing composition. -IPC_MESSAGE_ROUTED3(InputMsg_ImeConfirmComposition, +// This message deletes the current composition, inserts specified text, and +// moves the cursor. +IPC_MESSAGE_ROUTED3(InputMsg_ImeCommitText, base::string16 /* text */, gfx::Range /* replacement_range */, - bool /* keep_selection */) + int /* relative_cursor_pos */) + +// This message inserts the ongoing composition. +IPC_MESSAGE_ROUTED1(InputMsg_ImeFinishComposingText, bool /* keep_selection */) // This message notifies the renderer that the next key event is bound to one // or more pre-defined edit commands. If the next key event is not handled @@ -262,6 +260,11 @@ IPC_MESSAGE_ROUTED0(InputMsg_ImeEventAck) IPC_MESSAGE_ROUTED0(InputMsg_RequestTextInputStateUpdate) #endif +// Request from browser to update the cursor and composition information. +IPC_MESSAGE_ROUTED2(InputMsg_RequestCompositionUpdate, + bool /* immediate request */, + bool /* monitor request */) + IPC_MESSAGE_ROUTED0(InputMsg_SyntheticGestureCompleted) // ----------------------------------------------------------------------------- @@ -281,7 +284,7 @@ IPC_MESSAGE_ROUTED1(InputHostMsg_SetTouchAction, // Sent by the compositor when input scroll events are dropped due to bounds // restrictions on the root scroll offset. IPC_MESSAGE_ROUTED1(InputHostMsg_DidOverscroll, - content::DidOverscrollParams /* params */) + ui::DidOverscrollParams /* params */) // Sent by the compositor when a fling animation is stopped. IPC_MESSAGE_ROUTED0(InputHostMsg_DidStopFlinging) diff --git a/chromium/content/common/inter_process_time_ticks_converter.h b/chromium/content/common/inter_process_time_ticks_converter.h index f21ddc8eee7..cc5de553350 100644 --- a/chromium/content/common/inter_process_time_ticks_converter.h +++ b/chromium/content/common/inter_process_time_ticks_converter.h @@ -17,8 +17,9 @@ class LocalTimeTicks; class RemoteTimeDelta; class RemoteTimeTicks; -// On Windows, TimeTicks are not consistent between processes. Often, the values -// on one process have a static offset relative to another. Occasionally, these +// On Windows, TimeTicks are not always consistent between processes as +// indicated by |TimeTicks::IsConsistentAcrossProcesses()|. Often, the values on +// one process have a static offset relative to another. Occasionally, these // offsets shift while running. // // To combat this, any TimeTicks values sent from the remote process to the diff --git a/chromium/content/common/layer_tree_settings_factory.cc b/chromium/content/common/layer_tree_settings_factory.cc new file mode 100644 index 00000000000..c6ebb32d762 --- /dev/null +++ b/chromium/content/common/layer_tree_settings_factory.cc @@ -0,0 +1,35 @@ +// 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/common/layer_tree_settings_factory.h" + +#include "base/strings/string_number_conversions.h" +#include "cc/base/switches.h" + +namespace content { + +// static +void LayerTreeSettingsFactory::SetTopControlsSettings( + cc::LayerTreeSettings& settings, + const base::CommandLine& cmd) { + if (cmd.HasSwitch(cc::switches::kTopControlsShowThreshold)) { + std::string top_threshold_str = + cmd.GetSwitchValueASCII(cc::switches::kTopControlsShowThreshold); + double show_threshold; + if (base::StringToDouble(top_threshold_str, &show_threshold) && + show_threshold >= 0.f && show_threshold <= 1.f) + settings.top_controls_show_threshold = show_threshold; + } + + if (cmd.HasSwitch(cc::switches::kTopControlsHideThreshold)) { + std::string top_threshold_str = + cmd.GetSwitchValueASCII(cc::switches::kTopControlsHideThreshold); + double hide_threshold; + if (base::StringToDouble(top_threshold_str, &hide_threshold) && + hide_threshold >= 0.f && hide_threshold <= 1.f) + settings.top_controls_hide_threshold = hide_threshold; + } +} + +} // namespace content diff --git a/chromium/content/common/layer_tree_settings_factory.h b/chromium/content/common/layer_tree_settings_factory.h new file mode 100644 index 00000000000..b97a10d92a4 --- /dev/null +++ b/chromium/content/common/layer_tree_settings_factory.h @@ -0,0 +1,27 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_COMMON_LAYER_TREE_SETTINGS_FACTORY_H_ +#define CONTENT_COMMON_LAYER_TREE_SETTINGS_FACTORY_H_ + +#include "base/command_line.h" +#include "base/macros.h" +#include "cc/trees/layer_tree_settings.h" +#include "content/common/content_export.h" + +namespace content { + +// LayerTreeSettingsFactory holds utilities functions to generate +// LayerTreeSettings. +class CONTENT_EXPORT LayerTreeSettingsFactory { + // TODO(xingliu): Refactor LayerTreeSettings generation logic. + // crbug.com/577985 + public: + static void SetTopControlsSettings(cc::LayerTreeSettings& settings, + const base::CommandLine& command_line); +}; + +} // namespace content + +#endif // CONTENT_COMMON_LAYER_TREE_SETTINGS_FACTORY_H_ diff --git a/chromium/content/common/manifest_manager_messages.h b/chromium/content/common/manifest_manager_messages.h index 67cf0d0ddb5..ae4a2d2a632 100644 --- a/chromium/content/common/manifest_manager_messages.h +++ b/chromium/content/common/manifest_manager_messages.h @@ -30,6 +30,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::Manifest) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(short_name) IPC_STRUCT_TRAITS_MEMBER(start_url) + IPC_STRUCT_TRAITS_MEMBER(scope) IPC_STRUCT_TRAITS_MEMBER(display) IPC_STRUCT_TRAITS_MEMBER(orientation) IPC_STRUCT_TRAITS_MEMBER(icons) @@ -47,23 +48,12 @@ IPC_STRUCT_TRAITS_END() IPC_MESSAGE_ROUTED1(ManifestManagerMsg_RequestManifest, int /* request_id */) -// The browser process requests whether the document loaded in the associated -// RenderFrame has a manifest link URL. The render process will respond with -// a HasManifestResponse IPC message, along with a bool indicating the presence -// of a manifest link, and the |request_id| that was initially given. -IPC_MESSAGE_ROUTED1(ManifestManagerMsg_HasManifest, - int /* request_id */) - // The render process' response to a RequestManifest. The |request_id| will -// match the one that was initially received. The |manifest| object will be an -// empty manifest in case of any failure. -IPC_MESSAGE_ROUTED2(ManifestManagerHostMsg_RequestManifestResponse, +// match the one that was initially received. |manifest_url| will be empty if +// there is no manifest specified in the associated RenderFrame's document. +// |manifest| will be empty if a manifest was specified, but could not be +// parsed correctly. +IPC_MESSAGE_ROUTED3(ManifestManagerHostMsg_RequestManifestResponse, int, /* request_id */ + GURL, /* manifest URL */ content::Manifest /* manifest */) - -// The render process' response to a HasManifest. The |request_id| is the one -// sent from the browser. The |bool| will be true if the current document has a -// manifest link URL, and false otherwise. -IPC_MESSAGE_ROUTED2(ManifestManagerHostMsg_HasManifestResponse, - int, /* request_id */ - bool /* true if the document has a manifest link */) diff --git a/chromium/content/common/manifest_util_unittest.cc b/chromium/content/common/manifest_util_unittest.cc new file mode 100644 index 00000000000..b4f1a0c5919 --- /dev/null +++ b/chromium/content/common/manifest_util_unittest.cc @@ -0,0 +1,77 @@ +// 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/common/manifest_util.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +namespace content { + +TEST(ManifestUtilTest, WebDisplayModeConversions) { + struct ReversibleConversion { + blink::WebDisplayMode display_mode; + std::string lowercase_display_mode_string; + } reversible_conversions[] = { + {blink::WebDisplayModeUndefined, ""}, + {blink::WebDisplayModeBrowser, "browser"}, + {blink::WebDisplayModeMinimalUi, "minimal-ui"}, + {blink::WebDisplayModeStandalone, "standalone"}, + {blink::WebDisplayModeFullscreen, "fullscreen"}, + }; + + for (const ReversibleConversion& conversion : reversible_conversions) { + EXPECT_EQ( + conversion.display_mode, + WebDisplayModeFromString(conversion.lowercase_display_mode_string)); + EXPECT_EQ(conversion.lowercase_display_mode_string, + WebDisplayModeToString(conversion.display_mode)); + } + + // WebDisplayModeFromString() should work with non-lowercase strings. + EXPECT_EQ(blink::WebDisplayModeFullscreen, + WebDisplayModeFromString("Fullscreen")); + + // WebDisplayModeFromString() should return + // blink::WebDisplayModeUndefined if the string isn't known. + EXPECT_EQ(blink::WebDisplayModeUndefined, + WebDisplayModeFromString("random")); +} + +TEST(ManifestUtilTest, WebScreenOrientationLockTypeConversions) { + struct ReversibleConversion { + blink::WebScreenOrientationLockType orientation; + std::string lowercase_orientation_string; + } reversible_conversions[] = { + {blink::WebScreenOrientationLockDefault, ""}, + {blink::WebScreenOrientationLockPortraitPrimary, "portrait-primary"}, + {blink::WebScreenOrientationLockPortraitSecondary, "portrait-secondary"}, + {blink::WebScreenOrientationLockLandscapePrimary, "landscape-primary"}, + {blink::WebScreenOrientationLockLandscapeSecondary, + "landscape-secondary"}, + {blink::WebScreenOrientationLockAny, "any"}, + {blink::WebScreenOrientationLockLandscape, "landscape"}, + {blink::WebScreenOrientationLockPortrait, "portrait"}, + {blink::WebScreenOrientationLockNatural, "natural"}, + }; + + for (const ReversibleConversion& conversion : reversible_conversions) { + EXPECT_EQ(conversion.orientation, + WebScreenOrientationLockTypeFromString( + conversion.lowercase_orientation_string)); + EXPECT_EQ(conversion.lowercase_orientation_string, + WebScreenOrientationLockTypeToString(conversion.orientation)); + } + + // WebScreenOrientationLockTypeFromString() should work with non-lowercase + // strings. + EXPECT_EQ(blink::WebScreenOrientationLockNatural, + WebScreenOrientationLockTypeFromString("Natural")); + + // WebScreenOrientationLockTypeFromString() should return + // blink::WebScreenOrientationLockDefault if the string isn't known. + EXPECT_EQ(blink::WebScreenOrientationLockDefault, + WebScreenOrientationLockTypeFromString("random")); +} + +} // namespace content diff --git a/chromium/content/common/media/OWNERS b/chromium/content/common/media/OWNERS index 5b281449c56..60a6a2318b3 100644 --- a/chromium/content/common/media/OWNERS +++ b/chromium/content/common/media/OWNERS @@ -6,3 +6,6 @@ per-file *_messages*.h=file://ipc/SECURITY_OWNERS per-file *_param_traits*.*=set noparent per-file *_param_traits*.*=file://ipc/SECURITY_OWNERS + +per-file *_struct_traits*.*=set noparent +per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS diff --git a/chromium/content/common/media/aec_dump_messages.h b/chromium/content/common/media/aec_dump_messages.h index f6031d0392c..0f98f272334 100644 --- a/chromium/content/common/media/aec_dump_messages.h +++ b/chromium/content/common/media/aec_dump_messages.h @@ -21,18 +21,9 @@ IPC_MESSAGE_CONTROL2(AecDumpMsg_EnableAecDump, int /* id */, IPC::PlatformFileForTransit /* file_handle */) -// The browser hands over a file handle to the consumer in the renderer -// identified by |id| to use for the event log. -IPC_MESSAGE_CONTROL2(WebRTCEventLogMsg_EnableEventLog, - int /* id */, - IPC::PlatformFileForTransit /* file_handle */) - // Tell the renderer to disable AEC dump in all consumers. IPC_MESSAGE_CONTROL0(AecDumpMsg_DisableAecDump) -// Tell the renderer to disable event log in all consumers. -IPC_MESSAGE_CONTROL0(WebRTCEventLogMsg_DisableEventLog) - // Messages sent from the renderer to the browser. // Registers a consumer with the browser. The consumer will then get a file @@ -40,13 +31,6 @@ IPC_MESSAGE_CONTROL0(WebRTCEventLogMsg_DisableEventLog) IPC_MESSAGE_CONTROL1(AecDumpMsg_RegisterAecDumpConsumer, int /* id */) -// Registers a consumer with the browser. The consumer will then get a file -// handle when the dump is enabled. -IPC_MESSAGE_CONTROL1(WebRTCEventLogMsg_RegisterEventLogConsumer, int /* id */) - // Unregisters a consumer with the browser. IPC_MESSAGE_CONTROL1(AecDumpMsg_UnregisterAecDumpConsumer, int /* id */) - -// Unregisters a consumer with the browser. -IPC_MESSAGE_CONTROL1(WebRTCEventLogMsg_UnregisterEventLogConsumer, int /* id */) diff --git a/chromium/content/common/media/cdm_messages.h b/chromium/content/common/media/cdm_messages.h index 97841fe32a0..136edf1614f 100644 --- a/chromium/content/common/media/cdm_messages.h +++ b/chromium/content/common/media/cdm_messages.h @@ -104,24 +104,16 @@ IPC_MESSAGE_CONTROL2(CdmHostMsg_DestroyCdm, // Messages from browser to render. -IPC_MESSAGE_ROUTED5(CdmMsg_SessionMessage, +IPC_MESSAGE_ROUTED4(CdmMsg_SessionMessage, int /* cdm_id */, std::string /* session_id */, media::MediaKeys::MessageType /* message_type */, - std::vector<uint8_t> /* message */, - GURL /* legacy_destination_url */) + std::vector<uint8_t> /* message */) IPC_MESSAGE_ROUTED2(CdmMsg_SessionClosed, int /* cdm_id */, std::string /* session_id */) -IPC_MESSAGE_ROUTED5(CdmMsg_LegacySessionError, - int /* cdm_id */, - std::string /* session_id */, - media::MediaKeys::Exception /* exception_code */, - uint32_t /* system_code */, - std::string /* error_message */) - IPC_MESSAGE_ROUTED4(CdmMsg_SessionKeysChange, int /* cdm_id */, std::string /* session_id */, diff --git a/chromium/content/common/media/media_devices.cc b/chromium/content/common/media/media_devices.cc new file mode 100644 index 00000000000..c4bb498a656 --- /dev/null +++ b/chromium/content/common/media/media_devices.cc @@ -0,0 +1,18 @@ +// 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/common/media/media_devices.h" + +namespace content { + +MediaDeviceInfo::MediaDeviceInfo(const std::string& device_id, + const std::string& label, + const std::string& group_id) + : device_id(device_id), label(label), group_id(group_id) {} + +bool operator==(const MediaDeviceInfo& first, const MediaDeviceInfo& second) { + return first.device_id == second.device_id && first.label == second.label; +} + +} // namespace content diff --git a/chromium/content/common/media/media_devices.h b/chromium/content/common/media/media_devices.h new file mode 100644 index 00000000000..39255d151a8 --- /dev/null +++ b/chromium/content/common/media/media_devices.h @@ -0,0 +1,39 @@ +// 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_COMMON_MEDIA_MEDIA_DEVICES_H_ +#define CONTENT_COMMON_MEDIA_MEDIA_DEVICES_H_ + +#include <string> +#include <vector> + +namespace content { + +enum MediaDeviceType { + MEDIA_DEVICE_TYPE_AUDIO_INPUT, + MEDIA_DEVICE_TYPE_VIDEO_INPUT, + MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, + NUM_MEDIA_DEVICE_TYPES, +}; + +struct MediaDeviceInfo { + MediaDeviceInfo(const std::string& device_id, + const std::string& label, + const std::string& group_id); + std::string device_id; + std::string label; + std::string group_id; +}; + +using MediaDeviceInfoArray = std::vector<MediaDeviceInfo>; + +bool operator==(const MediaDeviceInfo& first, const MediaDeviceInfo& second); + +inline bool IsValidMediaDeviceType(MediaDeviceType type) { + return type >= 0 && type < NUM_MEDIA_DEVICE_TYPES; +} + +} // namespace content + +#endif // CONTENT_COMMON_MEDIA_MEDIA_DEVICES_H_ diff --git a/chromium/content/common/media/media_metadata_sanitizer.cc b/chromium/content/common/media/media_metadata_sanitizer.cc new file mode 100644 index 00000000000..16f548179d8 --- /dev/null +++ b/chromium/content/common/media/media_metadata_sanitizer.cc @@ -0,0 +1,110 @@ +// 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/common/media/media_metadata_sanitizer.h" + +#include <algorithm> +#include <string> + +#include "content/public/common/media_metadata.h" + +namespace content { + +namespace { + +// Maximum length for all the strings inside the MediaMetadata when it is sent +// over IPC. The renderer process should truncate the strings before sending +// the MediaMetadata and the browser process must do the same when receiving +// it. +const size_t kMaxIPCStringLength = 4 * 1024; + +// Maximum type length of Artwork, which conforms to RFC 4288 +// (https://tools.ietf.org/html/rfc4288). +const size_t kMaxArtworkTypeLength = 2 * 127 + 1; + +// Maximum number of artwork images inside the MediaMetadata. +const size_t kMaxNumberOfArtworkImages = 10; + +// Maximum of sizes in an artwork image. +const size_t kMaxNumberOfArtworkSizes = 10; + +bool CheckArtworkSrcSanity(const GURL& src) { + if (!src.is_valid()) + return false; + if (!src.SchemeIsHTTPOrHTTPS() && !src.SchemeIs(url::kDataScheme)) + return false; + if (src.spec().size() > url::kMaxURLChars) + return false; + + return true; +} + +bool CheckArtworkSanity(const MediaMetadata::Artwork& artwork) { + if (!CheckArtworkSrcSanity(artwork.src)) + return false; + if (artwork.type.size() > kMaxArtworkTypeLength) + return false; + if (artwork.sizes.size() > kMaxNumberOfArtworkSizes) + return false; + + return true; +} + +// Sanitize artwork. The method should not be called if |artwork.src| is bad. +MediaMetadata::Artwork SanitizeArtwork(const MediaMetadata::Artwork& artwork) { + MediaMetadata::Artwork sanitized_artwork; + + sanitized_artwork.src = artwork.src; + sanitized_artwork.type = artwork.type.substr(0, kMaxArtworkTypeLength); + for (const auto& size : artwork.sizes) { + sanitized_artwork.sizes.push_back(size); + if (sanitized_artwork.sizes.size() == kMaxNumberOfArtworkSizes) + break; + } + + return sanitized_artwork; +} + +} // anonymous namespace + +bool MediaMetadataSanitizer::CheckSanity(const MediaMetadata& metadata) { + if (metadata.title.size() > kMaxIPCStringLength) + return false; + if (metadata.artist.size() > kMaxIPCStringLength) + return false; + if (metadata.album.size() > kMaxIPCStringLength) + return false; + if (metadata.artwork.size() > kMaxNumberOfArtworkImages) + return false; + + for (const auto& artwork : metadata.artwork) { + if (!CheckArtworkSanity(artwork)) + return false; + } + + return true; +} + +MediaMetadata MediaMetadataSanitizer::Sanitize(const MediaMetadata& metadata) { + MediaMetadata sanitized_metadata; + + sanitized_metadata.title = metadata.title.substr(0, kMaxIPCStringLength); + sanitized_metadata.artist = metadata.artist.substr(0, kMaxIPCStringLength); + sanitized_metadata.album = metadata.album.substr(0, kMaxIPCStringLength); + + for (const auto& artwork : metadata.artwork) { + if (!CheckArtworkSrcSanity(artwork.src)) + continue; + + sanitized_metadata.artwork.push_back( + CheckArtworkSanity(artwork) ? artwork : SanitizeArtwork(artwork)); + + if (sanitized_metadata.artwork.size() == kMaxNumberOfArtworkImages) + break; + } + + return sanitized_metadata; +} + +} // namespace content diff --git a/chromium/content/common/media/media_metadata_sanitizer.h b/chromium/content/common/media/media_metadata_sanitizer.h new file mode 100644 index 00000000000..6a4d678b25f --- /dev/null +++ b/chromium/content/common/media/media_metadata_sanitizer.h @@ -0,0 +1,23 @@ +// 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_COMMON_MEDIA_MEDIA_METADATA_SANITIZER_H_ +#define CONTENT_COMMON_MEDIA_MEDIA_METADATA_SANITIZER_H_ + +namespace content { + +struct MediaMetadata; + +class MediaMetadataSanitizer { + public: + // Check the sanity of |metadata|. + static bool CheckSanity(const MediaMetadata& metadata); + + // Sanitizes |metadata| and return the result. + static MediaMetadata Sanitize(const MediaMetadata& metadata); +}; + +} // namespace content + +#endif // CONTENT_COMMON_MEDIA_MEDIA_METADATA_SANITIZER_H_ diff --git a/chromium/content/common/media/media_player_delegate_messages.h b/chromium/content/common/media/media_player_delegate_messages.h index 98d5d47ee94..8229b62ea56 100644 --- a/chromium/content/common/media/media_player_delegate_messages.h +++ b/chromium/content/common/media/media_player_delegate_messages.h @@ -8,14 +8,17 @@ #include <stdint.h> -#include "base/time/time.h" #include "content/common/content_export.h" #include "ipc/ipc_message_macros.h" +#include "media/base/media_content_type.h" #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT #define IPC_MESSAGE_START MediaPlayerDelegateMsgStart +IPC_ENUM_TRAITS_MAX_VALUE(media::MediaContentType, + media::MediaContentType::Uncontrollable) + // ---------------------------------------------------------------------------- // Messages from the browser to the renderer requesting playback state changes. // ---------------------------------------------------------------------------- @@ -48,4 +51,4 @@ IPC_MESSAGE_ROUTED5(MediaPlayerDelegateHostMsg_OnMediaPlaying, bool /* has_video */, bool /* has_audio */, bool /* is_remote */, - base::TimeDelta /* duration */) + media::MediaContentType /* media_content_type */) diff --git a/chromium/content/common/media/media_player_messages_android.h b/chromium/content/common/media/media_player_messages_android.h index 0aab6d85a5d..b1738c1ea6d 100644 --- a/chromium/content/common/media/media_player_messages_android.h +++ b/chromium/content/common/media/media_player_messages_android.h @@ -8,8 +8,6 @@ #include "base/time/time.h" #include "content/common/content_export.h" #include "ipc/ipc_message_macros.h" -#include "media/base/android/demuxer_stream_player_params.h" -#include "media/base/decrypt_config.h" #include "media/blink/renderer_media_player_interface.h" #include "media/gpu/ipc/common/media_param_traits.h" #include "ui/gfx/geometry/rect_f.h" @@ -19,45 +17,6 @@ #define IPC_MESSAGE_EXPORT CONTENT_EXPORT #define IPC_MESSAGE_START MediaPlayerMsgStart -IPC_ENUM_TRAITS(media::AudioCodec) -IPC_ENUM_TRAITS(media::DemuxerStream::Status) -IPC_ENUM_TRAITS(media::DemuxerStream::Type) -IPC_ENUM_TRAITS(media::VideoCodec) - -IPC_STRUCT_TRAITS_BEGIN(media::DemuxerConfigs) - IPC_STRUCT_TRAITS_MEMBER(audio_codec) - IPC_STRUCT_TRAITS_MEMBER(audio_channels) - IPC_STRUCT_TRAITS_MEMBER(audio_sampling_rate) - IPC_STRUCT_TRAITS_MEMBER(is_audio_encrypted) - IPC_STRUCT_TRAITS_MEMBER(audio_extra_data) - IPC_STRUCT_TRAITS_MEMBER(audio_codec_delay_ns) - IPC_STRUCT_TRAITS_MEMBER(audio_seek_preroll_ns) - - IPC_STRUCT_TRAITS_MEMBER(video_codec) - IPC_STRUCT_TRAITS_MEMBER(video_size) - IPC_STRUCT_TRAITS_MEMBER(is_video_encrypted) - IPC_STRUCT_TRAITS_MEMBER(video_extra_data) - - IPC_STRUCT_TRAITS_MEMBER(duration) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(media::DemuxerData) - IPC_STRUCT_TRAITS_MEMBER(type) - IPC_STRUCT_TRAITS_MEMBER(access_units) - IPC_STRUCT_TRAITS_MEMBER(demuxer_configs) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(media::AccessUnit) - IPC_STRUCT_TRAITS_MEMBER(status) - IPC_STRUCT_TRAITS_MEMBER(is_end_of_stream) - IPC_STRUCT_TRAITS_MEMBER(data) - IPC_STRUCT_TRAITS_MEMBER(timestamp) - IPC_STRUCT_TRAITS_MEMBER(key_id) - IPC_STRUCT_TRAITS_MEMBER(iv) - IPC_STRUCT_TRAITS_MEMBER(subsamples) - IPC_STRUCT_TRAITS_MEMBER(is_key_frame) -IPC_STRUCT_TRAITS_END() - IPC_ENUM_TRAITS_MAX_VALUE(MediaPlayerHostMsg_Initialize_Type, MEDIA_PLAYER_TYPE_LAST) @@ -65,13 +24,11 @@ IPC_ENUM_TRAITS_MAX_VALUE(MediaPlayerHostMsg_Initialize_Type, IPC_STRUCT_BEGIN(MediaPlayerHostMsg_Initialize_Params) IPC_STRUCT_MEMBER(MediaPlayerHostMsg_Initialize_Type, type) IPC_STRUCT_MEMBER(int, player_id) - IPC_STRUCT_MEMBER(int, demuxer_client_id) IPC_STRUCT_MEMBER(GURL, url) IPC_STRUCT_MEMBER(GURL, first_party_for_cookies) IPC_STRUCT_MEMBER(GURL, frame_url) IPC_STRUCT_MEMBER(bool, allow_credentials) IPC_STRUCT_MEMBER(int, delegate_id) - IPC_STRUCT_MEMBER(int, media_session_id) IPC_STRUCT_END() // Chrome for Android seek message sequence is: @@ -92,26 +49,6 @@ IPC_STRUCT_END() // seek flow, above, keeping web apps aware of seeks. These requests are // also allowed while another actual seek is in progress. // -// If the demuxer is located in the renderer, as in media source players, the -// browser must ensure the renderer demuxer is appropriately seeked between -// receipt of MediaPlayerHostMsg_Seek and transmission of -// MediaPlayerMsg_SeekCompleted. The following two renderer-demuxer control -// messages book-end the renderer-demuxer seek: -// 1.1 Browser->Renderer MediaPlayerMsg_DemuxerSeekRequest -// 1.2 Renderer->Browser MediaPlayerHostMsg_DemuxerSeekDone - -// Only in short-term hack to seek to reach I-Frame to feed a newly constructed -// video decoder may the above IPC sequence be modified to exclude SeekRequest, -// Seek and SeekCompleted, with condition that DemuxerSeekRequest's -// |is_browser_seek| parameter be true. Regular seek messages must still be -// handled even when a hack browser seek is in progress. In this case, the -// browser seek request's |time_to_seek| may no longer be buffered and the -// demuxer may instead seek to a future buffered time. The resulting -// DemuxerSeekDone message's |actual_browser_seek_time| is the time actually -// seeked-to, and is only meaningful for these hack browser seeks. -// TODO(wolenetz): Instead of doing browser seek, replay cached data since last -// keyframe. See http://crbug.com/304234. - // Messages for notifying the render process of media playback status ------- // Media buffering has updated. @@ -158,9 +95,6 @@ IPC_MESSAGE_ROUTED3(MediaPlayerMsg_MediaTimeUpdate, base::TimeDelta /* current_timestamp */, base::TimeTicks /* current_time_ticks */) -// A new key is required in order to continue decrypting encrypted content. -IPC_MESSAGE_ROUTED1(MediaPlayerMsg_WaitingForDecryptionKey, int /* player_id */) - // The player has been released. IPC_MESSAGE_ROUTED1(MediaPlayerMsg_MediaPlayerReleased, int /* player_id */) @@ -177,17 +111,6 @@ IPC_MESSAGE_ROUTED1(MediaPlayerMsg_DidMediaPlayerPlay, IPC_MESSAGE_ROUTED1(MediaPlayerMsg_DidMediaPlayerPause, int /* player_id */) -// Requests renderer demuxer seek. -IPC_MESSAGE_CONTROL3(MediaPlayerMsg_DemuxerSeekRequest, - int /* demuxer_client_id */, - base::TimeDelta /* time_to_seek */, - bool /* is_browser_seek */) - -// The media source player reads data from demuxer -IPC_MESSAGE_CONTROL2(MediaPlayerMsg_ReadFromDemuxer, - int /* demuxer_client_id */, - media::DemuxerStream::Type /* type */) - // Clank has connected to the remote device. IPC_MESSAGE_ROUTED2(MediaPlayerMsg_ConnectedToRemoteDevice, int /* player_id */, @@ -248,43 +171,8 @@ IPC_MESSAGE_ROUTED1(MediaPlayerHostMsg_EnterFullscreen, int /* player_id */) // Play the media on a remote device, if possible. IPC_MESSAGE_ROUTED1(MediaPlayerHostMsg_RequestRemotePlayback, - int /* demuxer_client_id */) + int /* player_id */) // Control media playing on a remote device. IPC_MESSAGE_ROUTED1(MediaPlayerHostMsg_RequestRemotePlaybackControl, - int /* demuxer_client_id */) - -// Requests the player with |player_id| to use the CDM with |cdm_id|. -IPC_MESSAGE_ROUTED2(MediaPlayerHostMsg_SetCdm, - int /* player_id */, - int /* cdm_id */) - -// Sent after the renderer demuxer has seeked. -IPC_MESSAGE_CONTROL2(MediaPlayerHostMsg_DemuxerSeekDone, - int /* demuxer_client_id */, - base::TimeDelta /* actual_browser_seek_time */) - -// Inform the media source player that the demuxer is ready. -IPC_MESSAGE_CONTROL2(MediaPlayerHostMsg_DemuxerReady, - int /* demuxer_client_id */, - media::DemuxerConfigs) - -// Sent when the data was read from the ChunkDemuxer. -IPC_MESSAGE_CONTROL2(MediaPlayerHostMsg_ReadFromDemuxerAck, - int /* demuxer_client_id */, - media::DemuxerData) - -// Inform the media source player of changed media duration from demuxer. -IPC_MESSAGE_CONTROL2(MediaPlayerHostMsg_DurationChanged, - int /* demuxer_client_id */, - base::TimeDelta /* duration */) - -#if defined(VIDEO_HOLE) -// Notify the player about the external surface, requesting it if necessary. -// |is_request| true if the player is requesting the external surface. -// |rect| the boundary rectangle of the video element. -IPC_MESSAGE_ROUTED3(MediaPlayerHostMsg_NotifyExternalSurface, - int /* player_id */, - bool /* is_request */, - gfx::RectF /* rect */) -#endif // defined(VIDEO_HOLE) + int /* player_id */) diff --git a/chromium/content/common/media/media_session.typemap b/chromium/content/common/media/media_session.typemap new file mode 100644 index 00000000000..b7566984935 --- /dev/null +++ b/chromium/content/common/media/media_session.typemap @@ -0,0 +1,11 @@ +# 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. + +mojom = "//third_party/WebKit/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 = [ + "blink.mojom.MediaImage=content::MediaMetadata::Artwork", + "blink.mojom.MediaMetadata=content::MediaMetadata", +] diff --git a/chromium/content/common/media/media_session_messages_android.h b/chromium/content/common/media/media_session_messages_android.h deleted file mode 100644 index 266ee273bcf..00000000000 --- a/chromium/content/common/media/media_session_messages_android.h +++ /dev/null @@ -1,43 +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. - -// IPC messages for the Media Session API. -// Multiply-included message file, hence no include guard. - -#include "content/common/android/gin_java_bridge_errors.h" -#include "content/common/content_export.h" -#include "content/public/common/media_metadata.h" -#include "ipc/ipc_message_macros.h" - -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT CONTENT_EXPORT -#define IPC_MESSAGE_START MediaSessionMsgStart - -IPC_STRUCT_TRAITS_BEGIN(content::MediaMetadata) - IPC_STRUCT_TRAITS_MEMBER(title) - IPC_STRUCT_TRAITS_MEMBER(artist) - IPC_STRUCT_TRAITS_MEMBER(album) -IPC_STRUCT_TRAITS_END() - -// Messages for notifying the render process of media session status ------- - -IPC_MESSAGE_ROUTED2(MediaSessionMsg_DidActivate, - int /* request_id */, - bool /* success */) - -IPC_MESSAGE_ROUTED1(MediaSessionMsg_DidDeactivate, int /* request_id */) - -// Messages for controlling the media session in browser process ---------- - -IPC_MESSAGE_ROUTED2(MediaSessionHostMsg_Activate, - int /* session_id */, - int /* request_id */) - -IPC_MESSAGE_ROUTED2(MediaSessionHostMsg_Deactivate, - int /* session_id */, - int /* request_id */) - -IPC_MESSAGE_ROUTED2(MediaSessionHostMsg_SetMetadata, - int /* request_id*/, - content::MediaMetadata /* metadata */) diff --git a/chromium/content/common/media/media_session_struct_traits.h b/chromium/content/common/media/media_session_struct_traits.h new file mode 100644 index 00000000000..bff354c9941 --- /dev/null +++ b/chromium/content/common/media/media_session_struct_traits.h @@ -0,0 +1,79 @@ +// 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_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" + +namespace mojo { + +template <> +struct StructTraits<blink::mojom::MediaImageDataView, + content::MediaMetadata::Artwork> { + static const GURL& src(const content::MediaMetadata::Artwork& artwork) { + return artwork.src; + } + + static const base::string16& type( + const content::MediaMetadata::Artwork& artwork) { + return artwork.type; + } + + static const std::vector<gfx::Size>& sizes( + const content::MediaMetadata::Artwork& artwork) { + return artwork.sizes; + } + + static bool Read(blink::mojom::MediaImageDataView data, + content::MediaMetadata::Artwork* out) { + if (!data.ReadSrc(&out->src)) + return false; + if (!data.ReadType(&out->type)) + return false; + if (!data.ReadSizes(&out->sizes)) + return false; + + return true; + } +}; + +template <> +struct StructTraits<blink::mojom::MediaMetadataDataView, + content::MediaMetadata> { + static const base::string16& title(const content::MediaMetadata& metadata) { + return metadata.title; + } + + static const base::string16& artist(const content::MediaMetadata& metadata) { + return metadata.artist; + } + + static const base::string16& album(const content::MediaMetadata& metadata) { + return metadata.album; + } + + static const std::vector<content::MediaMetadata::Artwork>& artwork( + const content::MediaMetadata& metadata) { + return metadata.artwork; + } + + static bool Read(blink::mojom::MediaMetadataDataView data, + content::MediaMetadata* out) { + if (!data.ReadTitle(&out->title)) + return false; + if (!data.ReadArtist(&out->artist)) + return false; + if (!data.ReadAlbum(&out->album)) + return false; + if (!data.ReadArtwork(&out->artwork)) + return false; + + return true; + } +}; + +} // namespace mojo + +#endif // CONTENT_COMMON_MEDIA_MEDIA_SESSION_STRUCT_TRAITS_H_ diff --git a/chromium/content/common/media/media_stream_messages.h b/chromium/content/common/media/media_stream_messages.h index 160c820844e..78c5e8c4ce8 100644 --- a/chromium/content/common/media/media_stream_messages.h +++ b/chromium/content/common/media/media_stream_messages.h @@ -43,6 +43,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::StreamDeviceInfo) IPC_STRUCT_TRAITS_MEMBER(device.type) IPC_STRUCT_TRAITS_MEMBER(device.name) IPC_STRUCT_TRAITS_MEMBER(device.id) + IPC_STRUCT_TRAITS_MEMBER(device.group_id) IPC_STRUCT_TRAITS_MEMBER(device.video_facing) IPC_STRUCT_TRAITS_MEMBER(device.matched_output_device_id) IPC_STRUCT_TRAITS_MEMBER(device.input.sample_rate) diff --git a/chromium/content/common/media/media_stream_options.cc b/chromium/content/common/media/media_stream_options.cc index 944d3d4b561..876a0d1f50c 100644 --- a/chromium/content/common/media/media_stream_options.cc +++ b/chromium/content/common/media/media_stream_options.cc @@ -39,21 +39,32 @@ StreamDeviceInfo::StreamDeviceInfo() StreamDeviceInfo::StreamDeviceInfo(MediaStreamType service_param, const std::string& name_param, + const std::string& device_param, + const std::string& group_param) + : device(service_param, device_param, name_param, group_param), + session_id(kNoId) {} + +StreamDeviceInfo::StreamDeviceInfo(MediaStreamType service_param, + const std::string& name_param, const std::string& device_param) - : device(service_param, device_param, name_param), - session_id(kNoId) { + : StreamDeviceInfo(service_param, name_param, device_param, std::string()) { } StreamDeviceInfo::StreamDeviceInfo(MediaStreamType service_param, const std::string& name_param, const std::string& device_param, + const std::string& group_param, int sample_rate, int channel_layout, int frames_per_buffer) - : device(service_param, device_param, name_param, sample_rate, - channel_layout, frames_per_buffer), - session_id(kNoId) { -} + : device(service_param, + device_param, + name_param, + group_param, + sample_rate, + channel_layout, + frames_per_buffer), + session_id(kNoId) {} // static bool StreamDeviceInfo::IsEqual(const StreamDeviceInfo& first, diff --git a/chromium/content/common/media/media_stream_options.h b/chromium/content/common/media/media_stream_options.h index dc458b5224a..5eb060697d1 100644 --- a/chromium/content/common/media/media_stream_options.h +++ b/chromium/content/common/media/media_stream_options.h @@ -70,6 +70,11 @@ struct CONTENT_EXPORT StreamDeviceInfo { StreamDeviceInfo(MediaStreamType service_param, const std::string& name_param, const std::string& device_param, + const std::string& group_param); + StreamDeviceInfo(MediaStreamType service_param, + const std::string& name_param, + const std::string& device_param, + const std::string& group_param, int sample_rate, int channel_layout, int frames_per_buffer); diff --git a/chromium/content/common/media/peer_connection_tracker_messages.h b/chromium/content/common/media/peer_connection_tracker_messages.h index cd774bea3fc..130f3b6ac4a 100644 --- a/chromium/content/common/media/peer_connection_tracker_messages.h +++ b/chromium/content/common/media/peer_connection_tracker_messages.h @@ -5,6 +5,7 @@ #include "base/values.h" #include "content/common/content_export.h" #include "ipc/ipc_message_macros.h" +#include "ipc/ipc_platform_file.h" #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT @@ -41,3 +42,8 @@ IPC_MESSAGE_CONTROL5(PeerConnectionTrackerHost_GetUserMedia, // Messages sent to PeerConnectionTracker. IPC_MESSAGE_CONTROL0(PeerConnectionTracker_GetAllStats) IPC_MESSAGE_CONTROL0(PeerConnectionTracker_OnSuspend) +IPC_MESSAGE_CONTROL2(PeerConnectionTracker_StartEventLog, + int /* peer_connection_local_id */, + IPC::PlatformFileForTransit /* file */) +IPC_MESSAGE_CONTROL1(PeerConnectionTracker_StopEventLog, + int /* peer_connection_local_id */) diff --git a/chromium/content/common/media/video_capture.h b/chromium/content/common/media/video_capture.h index 36312731535..09632c440a0 100644 --- a/chromium/content/common/media/video_capture.h +++ b/chromium/content/common/media/video_capture.h @@ -23,9 +23,9 @@ using VideoCaptureDeliverFrameCB = // browser process and renderer process. Browser process sends information about // the current capture state and error to the renderer process using this type. enum VideoCaptureState { - VIDEO_CAPTURE_STATE_STARTING, VIDEO_CAPTURE_STATE_STARTED, VIDEO_CAPTURE_STATE_PAUSED, + VIDEO_CAPTURE_STATE_RESUMED, VIDEO_CAPTURE_STATE_STOPPING, VIDEO_CAPTURE_STATE_STOPPED, VIDEO_CAPTURE_STATE_ERROR, diff --git a/chromium/content/common/media/video_capture_messages.h b/chromium/content/common/media/video_capture_messages.h index 4ff6f01d80d..1c92066c252 100644 --- a/chromium/content/common/media/video_capture_messages.h +++ b/chromium/content/common/media/video_capture_messages.h @@ -72,7 +72,7 @@ IPC_MESSAGE_CONTROL2(VideoCaptureMsg_FreeBuffer, int /* buffer_id */) // Tell the renderer process that a Buffer is available from video capture, and -// send the associated VideoFrame constituient parts as IPC parameters. +// send the associated VideoFrame constituent parts as IPC parameters. IPC_MESSAGE_CONTROL1(VideoCaptureMsg_BufferReady, VideoCaptureMsg_BufferReady_Params) @@ -95,10 +95,6 @@ IPC_MESSAGE_CONTROL3(VideoCaptureHostMsg_Start, media::VideoCaptureSessionId, /* session_id */ media::VideoCaptureParams /* params */) -// Pause the video capture specified by |device_id|. -IPC_MESSAGE_CONTROL1(VideoCaptureHostMsg_Pause, - int /* device_id */) - // Resume the video capture specified by |device_id|, |session_id| and // |params|. IPC_MESSAGE_CONTROL3(VideoCaptureHostMsg_Resume, @@ -106,15 +102,6 @@ IPC_MESSAGE_CONTROL3(VideoCaptureHostMsg_Resume, media::VideoCaptureSessionId, /* session_id */ media::VideoCaptureParams /* params */) -// Requests that the video capturer send a frame "soon" (e.g., to resolve -// picture loss or quality issues). -IPC_MESSAGE_CONTROL1(VideoCaptureHostMsg_RequestRefreshFrame, - int /* device_id */) - -// Close the video capture specified by |device_id|. -IPC_MESSAGE_CONTROL1(VideoCaptureHostMsg_Stop, - int /* device_id */) - // Tell the browser process that the renderer has finished reading from // a buffer previously delivered by VideoCaptureMsg_BufferReady. IPC_MESSAGE_CONTROL4(VideoCaptureHostMsg_BufferReady, diff --git a/chromium/content/common/media/webrtc_identity_messages.h b/chromium/content/common/media/webrtc_identity_messages.h deleted file mode 100644 index be532b9f2e4..00000000000 --- a/chromium/content/common/media/webrtc_identity_messages.h +++ /dev/null @@ -1,41 +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. - -// IPC messages for requesting WebRTC identity. -// Multiply-included message file, hence no include guard. - -#include "content/common/content_export.h" -#include "ipc/ipc_message_macros.h" -#include "url/gurl.h" - -#define IPC_MESSAGE_START WebRTCIdentityMsgStart -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT CONTENT_EXPORT - -IPC_STRUCT_BEGIN(WebRTCIdentityMsg_RequestIdentity_Params) - IPC_STRUCT_MEMBER(int, request_id) - IPC_STRUCT_MEMBER(GURL, url) - IPC_STRUCT_MEMBER(GURL, first_party_for_cookies) - IPC_STRUCT_MEMBER(std::string, identity_name) - IPC_STRUCT_MEMBER(std::string, common_name) -IPC_STRUCT_END() - -// Messages sent from the renderer to the browser. -// Request a WebRTC identity. -IPC_MESSAGE_CONTROL1(WebRTCIdentityMsg_RequestIdentity, - WebRTCIdentityMsg_RequestIdentity_Params) - -// Cancel the WebRTC identity request. -IPC_MESSAGE_CONTROL0(WebRTCIdentityMsg_CancelRequest) - -// Messages sent from the browser to the renderer. -// Return a WebRTC identity. -IPC_MESSAGE_CONTROL3(WebRTCIdentityHostMsg_IdentityReady, - int /* request_id */, - std::string /* certificate */, - std::string /* private_key */) -// Notifies an error from the identity request. -IPC_MESSAGE_CONTROL2(WebRTCIdentityHostMsg_RequestFailed, - int /* request_id */, - int /* error */) diff --git a/chromium/content/common/memory_coordinator.mojom b/chromium/content/common/memory_coordinator.mojom new file mode 100644 index 00000000000..82d40b97d67 --- /dev/null +++ b/chromium/content/common/memory_coordinator.mojom @@ -0,0 +1,14 @@ +// 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. + +module content.mojom; + +import "content/common/child_memory_coordinator.mojom"; + +// An interface to access the central memory coordinator from a child process. +// The browser process creates a handle for each child process. +interface MemoryCoordinatorHandle { + // A child process calls this method when ChildMemoryCoordinator is created. + AddChild(ChildMemoryCoordinator child); +}; diff --git a/chromium/content/common/mojo/embedded_application_runner.h b/chromium/content/common/mojo/embedded_application_runner.h deleted file mode 100644 index 017f093bfb1..00000000000 --- a/chromium/content/common/mojo/embedded_application_runner.h +++ /dev/null @@ -1,64 +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_COMMON_MOJO_EMBEDDED_APPLICATION_RUNNER_H_ -#define CONTENT_COMMON_MOJO_EMBEDDED_APPLICATION_RUNNER_H_ - -#include <memory> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_piece.h" -#include "content/public/common/mojo_application_info.h" -#include "services/shell/public/cpp/shell_client.h" -#include "services/shell/public/interfaces/shell_client.mojom.h" - -namespace content { - -// Hosts an in-process application instance that supports multiple ShellClient -// connections. The first incoming connection will invoke a provided factory -// function to instantiate the application, and the application will -// automatically be torn down when its last connection is lost. The application -// may be launched and torn down multiple times by a single -// EmbeddedApplicationRunner instance. -class EmbeddedApplicationRunner { - public: - // Constructs a runner which hosts a Mojo application. If an existing instance - // of the app is not running when an incoming connection is made, details from - // |info| will be used to construct a new instance. - EmbeddedApplicationRunner(const base::StringPiece& name, - const MojoApplicationInfo& info); - ~EmbeddedApplicationRunner(); - - // Binds an incoming ShellClientRequest for this application. If the - // application isn't already running, it's started. Otherwise the request is - // bound to the running instance. - void BindShellClientRequest(shell::mojom::ShellClientRequest request); - - // Sets a callback to run after the application loses its last connection and - // is torn down. - void SetQuitClosure(const base::Closure& quit_closure); - - private: - class Instance; - - void OnQuit(); - - // A reference to the application instance which may operate on the - // |application_task_runner_|'s thread. - scoped_refptr<Instance> instance_; - - base::Closure quit_closure_; - - base::WeakPtrFactory<EmbeddedApplicationRunner> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(EmbeddedApplicationRunner); -}; - -} // namespace content - -#endif // CONTENT_COMMON_MOJO_EMBEDDED_APPLICATION_RUNNER_H_ diff --git a/chromium/content/common/mojo/mojo_shell_connection_impl.cc b/chromium/content/common/mojo/mojo_shell_connection_impl.cc deleted file mode 100644 index 6c5ef64a781..00000000000 --- a/chromium/content/common/mojo/mojo_shell_connection_impl.cc +++ /dev/null @@ -1,202 +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/common/mojo/mojo_shell_connection_impl.h" - -#include "base/bind.h" -#include "base/lazy_instance.h" -#include "base/memory/ptr_util.h" -#include "base/threading/thread_local.h" -#include "content/common/mojo/embedded_application_runner.h" -#include "services/shell/public/cpp/shell_client.h" -#include "services/shell/public/cpp/shell_connection.h" -#include "services/shell/runner/common/client_util.h" - -namespace content { -namespace { - -using MojoShellConnectionPtr = - base::ThreadLocalPointer<MojoShellConnection>; - -// Env is thread local so that aura may be used on multiple threads. -base::LazyInstance<MojoShellConnectionPtr>::Leaky lazy_tls_ptr = - LAZY_INSTANCE_INITIALIZER; - -MojoShellConnection::Factory* mojo_shell_connection_factory = nullptr; - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnection, public: - -// static -void MojoShellConnection::SetForProcess( - std::unique_ptr<MojoShellConnection> connection) { - DCHECK(!lazy_tls_ptr.Pointer()->Get()); - lazy_tls_ptr.Pointer()->Set(connection.release()); -} - -// static -MojoShellConnection* MojoShellConnection::GetForProcess() { - return lazy_tls_ptr.Pointer()->Get(); -} - -// static -void MojoShellConnection::DestroyForProcess() { - // This joins the shell controller thread. - delete GetForProcess(); - lazy_tls_ptr.Pointer()->Set(nullptr); -} - -// static -void MojoShellConnection::SetFactoryForTest(Factory* factory) { - DCHECK(!lazy_tls_ptr.Pointer()->Get()); - mojo_shell_connection_factory = factory; -} - -// static -std::unique_ptr<MojoShellConnection> MojoShellConnection::Create( - shell::mojom::ShellClientRequest request) { - if (mojo_shell_connection_factory) - return mojo_shell_connection_factory->Run(); - return base::WrapUnique(new MojoShellConnectionImpl(std::move(request))); -} - -MojoShellConnection::~MojoShellConnection() {} - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnectionImpl, public: - -MojoShellConnectionImpl::MojoShellConnectionImpl( - shell::mojom::ShellClientRequest request) - : shell_connection_(new shell::ShellConnection(this, std::move(request))) {} - -MojoShellConnectionImpl::~MojoShellConnectionImpl() {} - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnectionImpl, shell::ShellClient implementation: - -void MojoShellConnectionImpl::Initialize(shell::Connector* connector, - const shell::Identity& identity, - uint32_t id) { - for (auto& client : embedded_shell_clients_) - client->Initialize(connector, identity, id); -} - -bool MojoShellConnectionImpl::AcceptConnection(shell::Connection* connection) { - std::string remote_app = connection->GetRemoteIdentity().name(); - if (remote_app == "mojo:shell") { - // Only expose the SCF interface to the shell. - connection->AddInterface<shell::mojom::ShellClientFactory>(this); - return true; - } - - bool accept = false; - for (auto& client : embedded_shell_clients_) - accept |= client->AcceptConnection(connection); - - // Reject all other connections to this application. - return accept; -} - -shell::InterfaceRegistry* -MojoShellConnectionImpl::GetInterfaceRegistryForConnection() { - // TODO(beng): This is really horrible since obviously subject to issues - // of ordering, but is no more horrible than this API is in general. - shell::InterfaceRegistry* registry = nullptr; - for (auto& client : embedded_shell_clients_) { - registry = client->GetInterfaceRegistryForConnection(); - if (registry) - return registry; - } - return nullptr; -} - -shell::InterfaceProvider* -MojoShellConnectionImpl::GetInterfaceProviderForConnection() { - // TODO(beng): This is really horrible since obviously subject to issues - // of ordering, but is no more horrible than this API is in general. - shell::InterfaceProvider* provider = nullptr; - for (auto& client : embedded_shell_clients_) { - provider = client->GetInterfaceProviderForConnection(); - if (provider) - return provider; - } - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnectionImpl, -// shell::InterfaceFactory<shell::mojom::ShellClientFactory> implementation: - -void MojoShellConnectionImpl::Create( - shell::Connection* connection, - shell::mojom::ShellClientFactoryRequest request) { - factory_bindings_.AddBinding(this, std::move(request)); -} - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnectionImpl, shell::mojom::ShellClientFactory implementation: - -void MojoShellConnectionImpl::CreateShellClient( - shell::mojom::ShellClientRequest request, - const mojo::String& name) { - auto it = request_handlers_.find(name); - if (it != request_handlers_.end()) - it->second.Run(std::move(request)); -} - -//////////////////////////////////////////////////////////////////////////////// -// MojoShellConnectionImpl, MojoShellConnection implementation: - -shell::ShellConnection* MojoShellConnectionImpl::GetShellConnection() { - return shell_connection_.get(); -} - -shell::Connector* MojoShellConnectionImpl::GetConnector() { - DCHECK(shell_connection_); - return shell_connection_->connector(); -} - -const shell::Identity& MojoShellConnectionImpl::GetIdentity() const { - DCHECK(shell_connection_); - return shell_connection_->identity(); -} - -void MojoShellConnectionImpl::SetConnectionLostClosure( - const base::Closure& closure) { - shell_connection_->SetConnectionLostClosure(closure); -} - -void MojoShellConnectionImpl::AddEmbeddedShellClient( - std::unique_ptr<shell::ShellClient> shell_client) { - embedded_shell_clients_.push_back(shell_client.get()); - owned_shell_clients_.push_back(std::move(shell_client)); -} - -void MojoShellConnectionImpl::AddEmbeddedShellClient( - shell::ShellClient* shell_client) { - embedded_shell_clients_.push_back(shell_client); -} - -void MojoShellConnectionImpl::AddEmbeddedService( - const std::string& name, - const MojoApplicationInfo& info) { - std::unique_ptr<EmbeddedApplicationRunner> app( - new EmbeddedApplicationRunner(name, info)); - AddShellClientRequestHandler( - name, base::Bind(&EmbeddedApplicationRunner::BindShellClientRequest, - base::Unretained(app.get()))); - auto result = embedded_apps_.insert(std::make_pair(name, std::move(app))); - DCHECK(result.second); -} - -void MojoShellConnectionImpl::AddShellClientRequestHandler( - const std::string& name, - const ShellClientRequestHandler& handler) { - auto result = request_handlers_.insert(std::make_pair(name, handler)); - DCHECK(result.second); -} - -} // namespace content diff --git a/chromium/content/common/mojo/mojo_shell_connection_impl.h b/chromium/content/common/mojo/mojo_shell_connection_impl.h deleted file mode 100644 index b20cd0ad4cb..00000000000 --- a/chromium/content/common/mojo/mojo_shell_connection_impl.h +++ /dev/null @@ -1,77 +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_COMMON_MOJO_SHELL_CONNECTION_IMPL_H_ -#define CONTENT_COMMON_MOJO_SHELL_CONNECTION_IMPL_H_ - -#include <memory> -#include <vector> - -#include "base/macros.h" -#include "content/public/common/mojo_shell_connection.h" -#include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "services/shell/public/cpp/shell_client.h" -#include "services/shell/public/cpp/shell_connection.h" -#include "services/shell/public/interfaces/shell_client_factory.mojom.h" - -namespace content { - -class EmbeddedApplicationRunner; - -class MojoShellConnectionImpl - : public MojoShellConnection, - public shell::ShellClient, - public shell::InterfaceFactory<shell::mojom::ShellClientFactory>, - public shell::mojom::ShellClientFactory { - - public: - explicit MojoShellConnectionImpl(shell::mojom::ShellClientRequest request); - ~MojoShellConnectionImpl() override; - - private: - // MojoShellConnection: - shell::ShellConnection* GetShellConnection() override; - shell::Connector* GetConnector() override; - const shell::Identity& GetIdentity() const override; - void SetConnectionLostClosure(const base::Closure& closure) override; - void AddEmbeddedShellClient( - std::unique_ptr<shell::ShellClient> shell_client) override; - void AddEmbeddedShellClient(shell::ShellClient* shell_client) override; - void AddEmbeddedService(const std::string& name, - const MojoApplicationInfo& info) override; - void AddShellClientRequestHandler( - const std::string& name, - const ShellClientRequestHandler& handler) override; - - // shell::ShellClient: - void Initialize(shell::Connector* connector, - const shell::Identity& identity, - uint32_t id) override; - bool AcceptConnection(shell::Connection* connection) override; - shell::InterfaceRegistry* GetInterfaceRegistryForConnection() override; - shell::InterfaceProvider* GetInterfaceProviderForConnection() override; - - // shell::InterfaceFactory<shell::mojom::ShellClientFactory>: - void Create(shell::Connection* connection, - shell::mojom::ShellClientFactoryRequest request) override; - - // shell::mojom::ShellClientFactory: - void CreateShellClient(shell::mojom::ShellClientRequest request, - const mojo::String& name) override; - - std::unique_ptr<shell::ShellConnection> shell_connection_; - mojo::BindingSet<shell::mojom::ShellClientFactory> factory_bindings_; - std::vector<shell::ShellClient*> embedded_shell_clients_; - std::vector<std::unique_ptr<shell::ShellClient>> owned_shell_clients_; - std::unordered_map<std::string, std::unique_ptr<EmbeddedApplicationRunner>> - embedded_apps_; - std::unordered_map<std::string, ShellClientRequestHandler> request_handlers_; - - DISALLOW_COPY_AND_ASSIGN(MojoShellConnectionImpl); -}; - -} // namespace content - -#endif // CONTENT_COMMON_MOJO_SHELL_CONNECTION_IMPL_H_ diff --git a/chromium/content/common/native_types.mojom b/chromium/content/common/native_types.mojom new file mode 100644 index 00000000000..222ee34803a --- /dev/null +++ b/chromium/content/common/native_types.mojom @@ -0,0 +1,24 @@ +// 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. + +module content.mojom; + +// This file is a collection of content types which rely on legacy IPC +// ParamTraits for serialization. All of these should eventually be converted to +// proper mojom definitions. + +[Native] +struct FrameOwnerProperties; + +[Native] +struct FrameReplicationState; + +[Native] +struct RendererPreferences; + +[Native] +struct ResizeParams; + +[Native] +struct WebPreferences; diff --git a/chromium/content/common/native_types.typemap b/chromium/content/common/native_types.typemap new file mode 100644 index 00000000000..ad8a5468737 --- /dev/null +++ b/chromium/content/common/native_types.typemap @@ -0,0 +1,42 @@ +# 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. + +mojom = "//content/common/native_types.mojom" +public_headers = [ + "//content/common/frame_owner_properties.h", + "//content/common/frame_replication_state.h", + "//content/common/resize_params.h", + "//content/public/common/renderer_preferences.h", + "//content/public/common/web_preferences.h", +] +traits_headers = [ + "//content/common/frame_messages.h", + "//content/common/view_messages.h", + "//content/public/common/common_param_traits.h", +] +public_deps = [ + # NOTE: These dependencies are here to satisfy gn check because + # common_param_traits_macros.h and/or view_messages.h include their headers. + # Although the mojo bindings target is configured to allow direct circular + # includes from //content/common and //content/public/common, this isn't a + # transitive allowance, so those targets' own public_deps aren't included in + # the set of implied dependencies. + "//cc/ipc", + "//media", + "//media/base/ipc", + "//ui/accessibility", + "//ui/base/ime:text_input_types", + "//ui/gfx/ipc", + "//ui/gfx/ipc/color", + "//ui/gfx/ipc/skia", + "//ui/surface", + "//url/ipc:url_ipc", +] +type_mappings = [ + "content.mojom.FrameOwnerProperties=content::FrameOwnerProperties", + "content.mojom.FrameReplicationState=content::FrameReplicationState", + "content.mojom.RendererPreferences=content::RendererPreferences", + "content.mojom.ResizeParams=content::ResizeParams", + "content.mojom.WebPreferences=content::WebPreferences", +] diff --git a/chromium/content/common/navigation_params.cc b/chromium/content/common/navigation_params.cc index ac2cb9cbe31..2518e72800b 100644 --- a/chromium/content/common/navigation_params.cc +++ b/chromium/content/common/navigation_params.cc @@ -18,11 +18,11 @@ namespace content { bool ShouldMakeNetworkRequestForURL(const GURL& url) { CHECK(IsBrowserSideNavigationEnabled()); - // Data URLs, Javascript URLs, about:blank, srcdoc should not send a request + // Javascript URLs, about:blank, srcdoc should not send a request // to the network stack. // TODO(clamy): same document navigations should not send requests to the // network stack. Neither should pushState/popState. - return !url.SchemeIs(url::kDataScheme) && url != GURL(url::kAboutBlankURL) && + return url != GURL(url::kAboutBlankURL) && !url.SchemeIs(url::kJavaScriptScheme) && !url.is_empty() && !url.SchemeIs(url::kContentIDScheme) && url != GURL(content::kAboutSrcDocURL); @@ -102,25 +102,15 @@ BeginNavigationParams::BeginNavigationParams( const BeginNavigationParams& other) = default; StartNavigationParams::StartNavigationParams() - : -#if defined(OS_ANDROID) - has_user_gesture(false), -#endif - transferred_request_child_id(-1), + : transferred_request_child_id(-1), transferred_request_request_id(-1) { } StartNavigationParams::StartNavigationParams( const std::string& extra_headers, -#if defined(OS_ANDROID) - bool has_user_gesture, -#endif int transferred_request_child_id, int transferred_request_request_id) : extra_headers(extra_headers), -#if defined(OS_ANDROID) - has_user_gesture(has_user_gesture), -#endif transferred_request_child_id(transferred_request_child_id), transferred_request_request_id(transferred_request_request_id) { } @@ -138,6 +128,7 @@ RequestNavigationParams::RequestNavigationParams() page_id(-1), nav_entry_id(0), is_same_document_history_load(false), + is_history_navigation_in_new_child(false), has_committed_real_load(false), intended_as_new_entry(false), pending_history_list_offset(-1), @@ -145,7 +136,9 @@ RequestNavigationParams::RequestNavigationParams() current_history_list_length(0), is_view_source(false), should_clear_history_list(false), - should_create_service_worker(false) {} + should_create_service_worker(false), + service_worker_provider_id(kInvalidServiceWorkerProviderId), + has_user_gesture(false) {} RequestNavigationParams::RequestNavigationParams( bool is_overriding_user_agent, @@ -156,13 +149,16 @@ RequestNavigationParams::RequestNavigationParams( int32_t page_id, int nav_entry_id, bool is_same_document_history_load, + bool is_history_navigation_in_new_child, + std::map<std::string, bool> subframe_unique_names, bool has_committed_real_load, bool intended_as_new_entry, int pending_history_list_offset, int current_history_list_offset, int current_history_list_length, bool is_view_source, - bool should_clear_history_list) + bool should_clear_history_list, + bool has_user_gesture) : is_overriding_user_agent(is_overriding_user_agent), redirects(redirects), can_load_local_resources(can_load_local_resources), @@ -171,6 +167,8 @@ RequestNavigationParams::RequestNavigationParams( page_id(page_id), nav_entry_id(nav_entry_id), is_same_document_history_load(is_same_document_history_load), + is_history_navigation_in_new_child(is_history_navigation_in_new_child), + subframe_unique_names(subframe_unique_names), has_committed_real_load(has_committed_real_load), intended_as_new_entry(intended_as_new_entry), pending_history_list_offset(pending_history_list_offset), @@ -178,7 +176,9 @@ RequestNavigationParams::RequestNavigationParams( current_history_list_length(current_history_list_length), is_view_source(is_view_source), should_clear_history_list(should_clear_history_list), - should_create_service_worker(false) {} + should_create_service_worker(false), + service_worker_provider_id(kInvalidServiceWorkerProviderId), + has_user_gesture(has_user_gesture) {} RequestNavigationParams::RequestNavigationParams( const RequestNavigationParams& other) = default; diff --git a/chromium/content/common/navigation_params.h b/chromium/content/common/navigation_params.h index f08c8bb393d..6fd86aafcd6 100644 --- a/chromium/content/common/navigation_params.h +++ b/chromium/content/common/navigation_params.h @@ -7,6 +7,7 @@ #include <stdint.h> +#include <map> #include <string> #include "base/memory/ref_counted.h" @@ -18,6 +19,7 @@ #include "content/public/common/page_state.h" #include "content/public/common/referrer.h" #include "content/public/common/request_context_type.h" +#include "content/public/common/resource_response.h" #include "ui/base/page_transition_types.h" #include "url/gurl.h" @@ -37,8 +39,8 @@ enum LoFiState { // PlzNavigate // Helper function to determine if the navigation to |url| should make a request -// to the network stack. A request should not be sent for data URLs, JavaScript -// URLs or about:blank. In these cases, no request needs to be sent. +// to the network stack. A request should not be sent for JavaScript URLs or +// about:blank. In these cases, no request needs to be sent. bool CONTENT_EXPORT ShouldMakeNetworkRequestForURL(const GURL& url); // The following structures hold parameters used during a navigation. In @@ -180,9 +182,6 @@ struct CONTENT_EXPORT BeginNavigationParams { struct CONTENT_EXPORT StartNavigationParams { StartNavigationParams(); StartNavigationParams(const std::string& extra_headers, -#if defined(OS_ANDROID) - bool has_user_gesture, -#endif int transferred_request_child_id, int transferred_request_request_id); StartNavigationParams(const StartNavigationParams& other); @@ -191,10 +190,6 @@ struct CONTENT_EXPORT StartNavigationParams { // Extra headers (separated by \n) to send during the request. std::string extra_headers; -#if defined(OS_ANDROID) - bool has_user_gesture; -#endif - // The following two members identify a previous request that has been // created before this navigation is being transferred to a new process. // This serves the purpose of recycling the old request. @@ -203,6 +198,16 @@ struct CONTENT_EXPORT StartNavigationParams { int transferred_request_request_id; }; +// PlzNavigate +// Timings collected in the browser during navigation for the +// Navigation Timing API. Sent to Blink in RequestNavigationParams when +// the navigation is ready to be committed. +struct CONTENT_EXPORT NavigationTiming { + base::TimeTicks redirect_start; + base::TimeTicks redirect_end; + base::TimeTicks fetch_start; +}; + // Used by FrameMsg_Navigate. Holds the parameters needed by the renderer to // start a browser-initiated navigation besides those in CommonNavigationParams. // PlzNavigate: sent to the renderer to make it issue a stream request for a @@ -217,13 +222,16 @@ struct CONTENT_EXPORT RequestNavigationParams { int32_t page_id, int nav_entry_id, bool is_same_document_history_load, + bool is_history_navigation_in_new_child, + std::map<std::string, bool> subframe_unique_names, bool has_committed_real_load, bool intended_as_new_entry, int pending_history_list_offset, int current_history_list_offset, int current_history_list_length, bool is_view_source, - bool should_clear_history_list); + bool should_clear_history_list, + bool has_user_gesture); RequestNavigationParams(const RequestNavigationParams& other); ~RequestNavigationParams(); @@ -234,6 +242,9 @@ struct CONTENT_EXPORT RequestNavigationParams { // navigations; defaults to empty. std::vector<GURL> redirects; + // The ResourceResponseInfos received during redirects. + std::vector<ResourceResponseInfo> redirect_response; + // Whether or not this url should be allowed to access local file:// // resources. bool can_load_local_resources; @@ -262,6 +273,20 @@ struct CONTENT_EXPORT RequestNavigationParams { // the same document. Defaults to false. bool is_same_document_history_load; + // Whether this is a history navigation in a newly created child frame, in + // which case the browser process is instructing the renderer process to load + // a URL from a session history item. Defaults to false. + bool is_history_navigation_in_new_child; + + // If this is a history navigation, this contains a map of frame unique names + // to |is_about_blank| for immediate children of the frame being navigated for + // which there are history items. The renderer process only needs to check + // with the browser process for newly created subframes that have these unique + // names (and only when not staying on about:blank). + // TODO(creis): Expand this to a data structure including corresponding + // same-process PageStates for the whole subtree in https://crbug.com/639842. + std::map<std::string, bool> subframe_unique_names; + // Whether the frame being navigated has already committed a real page, which // affects how new navigations are classified in the renderer process. // This currently is only ever set to true in --site-per-process mode. @@ -298,6 +323,20 @@ struct CONTENT_EXPORT RequestNavigationParams { // Whether a ServiceWorkerProviderHost should be created for the window. bool should_create_service_worker; + // PlzNavigate + // Timing of navigation events. + NavigationTiming navigation_timing; + + // PlzNavigate + // The ServiceWorkerProviderHost ID used for navigations, if it was already + // created by the browser. Set to kInvalidServiceWorkerProviderId otherwise. + // This parameter is not used in the current navigation architecture, where + // it will always be equal to kInvalidServiceWorkerProviderId. + int service_worker_provider_id; + + // True if the navigation originated due to a user gesture. + bool has_user_gesture; + #if defined(OS_ANDROID) // The real content of the data: URL. Only used in Android WebView for // implementing LoadDataWithBaseUrl API method to circumvent the restriction diff --git a/chromium/content/common/navigation_params_unittest.cc b/chromium/content/common/navigation_params_unittest.cc index 0dec5df6b9e..ee1f96a68e0 100644 --- a/chromium/content/common/navigation_params_unittest.cc +++ b/chromium/content/common/navigation_params_unittest.cc @@ -16,8 +16,8 @@ TEST(NavigationParamsTest, ShouldMakeNetworkRequestForURL) { EXPECT_TRUE(ShouldMakeNetworkRequestForURL(GURL("http://foo/bar.html"))); EXPECT_TRUE(ShouldMakeNetworkRequestForURL(GURL("https://foo/bar.html"))); + EXPECT_TRUE(ShouldMakeNetworkRequestForURL(GURL("data://foo"))); - EXPECT_FALSE(ShouldMakeNetworkRequestForURL(GURL("data://foo"))); EXPECT_FALSE(ShouldMakeNetworkRequestForURL(GURL("about:blank"))); EXPECT_FALSE(ShouldMakeNetworkRequestForURL(GURL("about:srcdoc"))); EXPECT_FALSE(ShouldMakeNetworkRequestForURL(GURL("javascript://foo.js"))); diff --git a/chromium/content/common/net/url_fetcher.cc b/chromium/content/common/net/url_fetcher.cc index 90a664c6931..f4bf457b26b 100644 --- a/chromium/content/common/net/url_fetcher.cc +++ b/chromium/content/common/net/url_fetcher.cc @@ -12,10 +12,9 @@ namespace content { namespace { -base::SupportsUserData::Data* CreateURLRequestUserData( - int render_process_id, - int render_view_id) { - return new URLRequestUserData(render_process_id, render_view_id); +base::SupportsUserData::Data* CreateURLRequestUserData(int render_process_id, + int render_frame_id) { + return new URLRequestUserData(render_process_id, render_frame_id); } } // namespace diff --git a/chromium/content/common/one_writer_seqlock.cc b/chromium/content/common/one_writer_seqlock.cc deleted file mode 100644 index fa0c8b2d0cf..00000000000 --- a/chromium/content/common/one_writer_seqlock.cc +++ /dev/null @@ -1,49 +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/common/one_writer_seqlock.h" - -namespace content { - -OneWriterSeqLock::OneWriterSeqLock() - : sequence_(0) { -} - -base::subtle::Atomic32 OneWriterSeqLock::ReadBegin() { - base::subtle::Atomic32 version; - for (;;) { - version = base::subtle::NoBarrier_Load(&sequence_); - - // If the counter is even, then the associated data might be in a - // consistent state, so we can try to read. - if ((version & 1) == 0) - break; - - // Otherwise, the writer is in the middle of an update. Retry the read. - base::PlatformThread::YieldCurrentThread(); - } - return version; -} - -bool OneWriterSeqLock::ReadRetry(base::subtle::Atomic32 version) { - // If the sequence number was updated then a read should be re-attempted. - // -- Load fence, read membarrier - return base::subtle::Release_Load(&sequence_) != version; -} - -void OneWriterSeqLock::WriteBegin() { - // Increment the sequence number to odd to indicate the beginning of a write - // update. - base::subtle::Barrier_AtomicIncrement(&sequence_, 1); - // -- Store fence, write membarrier -} - -void OneWriterSeqLock::WriteEnd() { - // Increment the sequence to an even number to indicate the completion of - // a write update. - // -- Store fence, write membarrier - base::subtle::Barrier_AtomicIncrement(&sequence_, 1); -} - -} // namespace content diff --git a/chromium/content/common/one_writer_seqlock.h b/chromium/content/common/one_writer_seqlock.h deleted file mode 100644 index e301e848d5c..00000000000 --- a/chromium/content/common/one_writer_seqlock.h +++ /dev/null @@ -1,47 +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_COMMON_ONE_WRITER_SEQLOCK_H_ -#define CONTENT_COMMON_ONE_WRITER_SEQLOCK_H_ - -#include "base/atomicops.h" -#include "base/macros.h" -#include "base/threading/platform_thread.h" -#include "content/common/content_export.h" - -namespace content { - -// This SeqLock handles only *one* writer and multiple readers. It may be -// suitable for low-contention with relatively infrequent writes, and many -// readers. See: -// http://en.wikipedia.org/wiki/Seqlock -// http://www.concurrencykit.org/doc/ck_sequence.html -// This implementation is based on ck_sequence.h from http://concurrencykit.org. -// -// Currently this type of lock is used in two implementations (gamepad and -// device motion, in particular see e.g. shared_memory_seqlock_buffer.h). -// It may make sense to generalize this lock to multiple writers. -// -// You must be very careful not to operate on potentially inconsistent read -// buffers. If the read must be retry'd, the data in the read buffer could -// contain any random garbage. e.g., contained pointers might be -// garbage, or indices could be out of range. Probably the only suitable thing -// to do during the read loop is to make a copy of the data, and operate on it -// only after the read was found to be consistent. -class CONTENT_EXPORT OneWriterSeqLock { - public: - OneWriterSeqLock(); - base::subtle::Atomic32 ReadBegin(); - bool ReadRetry(base::subtle::Atomic32 version); - void WriteBegin(); - void WriteEnd(); - - private: - base::subtle::Atomic32 sequence_; - DISALLOW_COPY_AND_ASSIGN(OneWriterSeqLock); -}; - -} // namespace content - -#endif // CONTENT_COMMON_ONE_WRITER_SEQLOCK_H_ diff --git a/chromium/content/common/one_writer_seqlock_unittest.cc b/chromium/content/common/one_writer_seqlock_unittest.cc deleted file mode 100644 index 84d5156a7bd..00000000000 --- a/chromium/content/common/one_writer_seqlock_unittest.cc +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/one_writer_seqlock.h" - -#include <stdlib.h> - -#include "base/atomic_ref_count.h" -#include "base/macros.h" -#include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/threading/platform_thread.h" -#include "build/build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -// Basic test to make sure that basic operation works correctly. - -struct TestData { - unsigned a, b, c; -}; - -class BasicSeqLockTestThread : public PlatformThread::Delegate { - public: - BasicSeqLockTestThread() {} - - void Init( - content::OneWriterSeqLock* seqlock, - TestData* data, - base::subtle::Atomic32* ready) { - seqlock_ = seqlock; - data_ = data; - ready_ = ready; - } - void ThreadMain() override { - while (AtomicRefCountIsZero(ready_)) { - PlatformThread::YieldCurrentThread(); - } - - for (unsigned i = 0; i < 1000; ++i) { - TestData copy; - base::subtle::Atomic32 version; - do { - version = seqlock_->ReadBegin(); - copy = *data_; - } while (seqlock_->ReadRetry(version)); - - EXPECT_EQ(copy.a + 100, copy.b); - EXPECT_EQ(copy.c, copy.b + copy.a); - } - - AtomicRefCountDec(ready_); - } - - private: - content::OneWriterSeqLock* seqlock_; - TestData* data_; - base::AtomicRefCount* ready_; - - DISALLOW_COPY_AND_ASSIGN(BasicSeqLockTestThread); -}; - -#if defined(OS_ANDROID) -#define MAYBE_ManyThreads FLAKY_ManyThreads -#else -#define MAYBE_ManyThreads ManyThreads -#endif -TEST(OneWriterSeqLockTest, MAYBE_ManyThreads) { - content::OneWriterSeqLock seqlock; - TestData data = { 0, 0, 0 }; - base::AtomicRefCount ready = 0; - - ANNOTATE_BENIGN_RACE_SIZED(&data, sizeof(data), "Racey reads are discarded"); - - static const unsigned kNumReaderThreads = 10; - BasicSeqLockTestThread threads[kNumReaderThreads]; - PlatformThreadHandle handles[kNumReaderThreads]; - - for (unsigned i = 0; i < kNumReaderThreads; ++i) - threads[i].Init(&seqlock, &data, &ready); - for (unsigned i = 0; i < kNumReaderThreads; ++i) - ASSERT_TRUE(PlatformThread::Create(0, &threads[i], &handles[i])); - - // The main thread is the writer, and the spawned are readers. - unsigned counter = 0; - for (;;) { - seqlock.WriteBegin(); - data.a = counter++; - data.b = data.a + 100; - data.c = data.b + data.a; - seqlock.WriteEnd(); - - if (counter == 1) - base::AtomicRefCountIncN(&ready, kNumReaderThreads); - - if (AtomicRefCountIsZero(&ready)) - break; - } - - for (unsigned i = 0; i < kNumReaderThreads; ++i) - PlatformThread::Join(handles[i]); -} - -} // namespace base diff --git a/chromium/content/common/origin_trials/trial_token.cc b/chromium/content/common/origin_trials/trial_token.cc index 65980de3575..ae11999ee3a 100644 --- a/chromium/content/common/origin_trials/trial_token.cc +++ b/chromium/content/common/origin_trials/trial_token.cc @@ -61,18 +61,14 @@ std::unique_ptr<TrialToken> TrialToken::From( return token; } -blink::WebOriginTrialTokenStatus TrialToken::IsValidForFeature( +blink::WebOriginTrialTokenStatus TrialToken::IsValid( const url::Origin& origin, - base::StringPiece feature_name, const base::Time& now) const { // The order of these checks is intentional. For example, will only report a - // token as expired if it is valid for the origin + feature combination. + // token as expired if it is valid for the origin. if (!ValidateOrigin(origin)) { return blink::WebOriginTrialTokenStatus::WrongOrigin; } - if (!ValidateFeatureName(feature_name)) { - return blink::WebOriginTrialTokenStatus::WrongFeature; - } if (!ValidateDate(now)) { return blink::WebOriginTrialTokenStatus::Expired; } @@ -161,6 +157,14 @@ std::unique_ptr<TrialToken> TrialToken::Parse( return nullptr; } + // The |isSubdomain| flag is optional. If found, ensure it is a valid boolean. + bool is_subdomain = false; + if (datadict->HasKey("isSubdomain")) { + if (!datadict->GetBoolean("isSubdomain", &is_subdomain)) { + return nullptr; + } + } + // Ensure that the feature name is a valid string. if (feature_name.empty()) { return nullptr; @@ -172,10 +176,15 @@ std::unique_ptr<TrialToken> TrialToken::Parse( } return base::WrapUnique( - new TrialToken(origin, feature_name, expiry_timestamp)); + new TrialToken(origin, is_subdomain, feature_name, expiry_timestamp)); } bool TrialToken::ValidateOrigin(const url::Origin& origin) const { + if (match_subdomains_) { + return origin.scheme() == origin_.scheme() && + origin.DomainIs(origin_.host()) && + origin.port() == origin_.port(); + } return origin == origin_; } @@ -207,9 +216,11 @@ bool TrialToken::ValidateSignature(base::StringPiece signature, } TrialToken::TrialToken(const url::Origin& origin, + bool match_subdomains, const std::string& feature_name, uint64_t expiry_timestamp) : origin_(origin), + match_subdomains_(match_subdomains), feature_name_(feature_name), expiry_time_(base::Time::FromDoubleT(expiry_timestamp)) {} diff --git a/chromium/content/common/origin_trials/trial_token.h b/chromium/content/common/origin_trials/trial_token.h index f563a6378a4..9e4f8244eab 100644 --- a/chromium/content/common/origin_trials/trial_token.h +++ b/chromium/content/common/origin_trials/trial_token.h @@ -19,14 +19,13 @@ enum class WebOriginTrialTokenStatus; namespace content { -// The Experimental Framework (EF) provides limited access to experimental -// features, on a per-origin basis (origin trials). This class defines the trial -// token data structure, used to securely provide access to an experimental -// feature. +// The Origin Trials Framework (OT) provides limited access to experimental +// features, on a per-origin basis. This class defines the trial token data +// structure, used to securely provide access to an experimental feature. // -// Features are defined by string names, provided by the implementers. The EF +// Features are defined by string names, provided by the implementers. The OT // code does not maintain an enum or constant list for feature names. Instead, -// the EF validates the name provided by the feature implementation against any +// it validates the name provided by the feature implementation against any // provided tokens. // // More documentation on the token format can be found at @@ -50,14 +49,13 @@ class CONTENT_EXPORT TrialToken { blink::WebOriginTrialTokenStatus* out_status); // Returns success if this token is appropriate for use by the given origin - // and feature name, and has not yet expired. Otherwise, the return value - // indicates why the token is not valid. - blink::WebOriginTrialTokenStatus IsValidForFeature( - const url::Origin& origin, - base::StringPiece feature_name, - const base::Time& now) const; + // and has not yet expired. Otherwise, the return value indicates why the + // token is not valid. + blink::WebOriginTrialTokenStatus IsValid(const url::Origin& origin, + const base::Time& now) const; url::Origin origin() { return origin_; } + bool match_subdomains() const { return match_subdomains_; } std::string feature_name() { return feature_name_; } base::Time expiry_time() { return expiry_time_; } @@ -87,12 +85,16 @@ class CONTENT_EXPORT TrialToken { private: TrialToken(const url::Origin& origin, + bool match_subdomains, const std::string& feature_name, uint64_t expiry_timestamp); // The origin for which this token is valid. Must be a secure origin. url::Origin origin_; + // Indicates if the token should match all subdomains of the origin. + bool match_subdomains_; + // The name of the experimental feature which this token enables. std::string feature_name_; diff --git a/chromium/content/common/origin_trials/trial_token_unittest.cc b/chromium/content/common/origin_trials/trial_token_unittest.cc index b3be991c754..b5d396c63aa 100644 --- a/chromium/content/common/origin_trials/trial_token_unittest.cc +++ b/chromium/content/common/origin_trials/trial_token_unittest.cc @@ -28,6 +28,13 @@ namespace { // 0x10, 0xac, 0xf9, 0x3a, 0x1c, 0xb8, 0xa9, 0x28, 0x70, 0xd2, 0x9a, // 0xd0, 0x0b, 0x59, 0xe1, 0xac, 0x2b, 0xb7, 0xd5, 0xca, 0x1f, 0x64, // 0x90, 0x08, 0x8e, 0xa8, 0xe0, 0x56, 0x3a, 0x04, 0xd0 +// +// This private key can also be found in tools/origin_trials/eftest.key in +// binary form. Please update that if changing the key. +// +// To use this with a real browser, use --origin-trial-public-key with the +// public key, base-64-encoded: +// --origin-trial-public-key=dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA= const uint8_t kTestPublicKey[] = { 0x75, 0x10, 0xac, 0xf9, 0x3a, 0x1c, 0xb8, 0xa9, 0x28, 0x70, 0xd2, 0x9a, 0xd0, 0x0b, 0x59, 0xe1, 0xac, 0x2b, 0xb7, 0xd5, 0xca, 0x1f, @@ -58,13 +65,39 @@ const char* kSampleToken = "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" "IjogMTQ1ODc2NjI3N30="; +// This is a good subdomain trial token, signed with the above test private key. +// Generate this token with the command (in tools/origin_trials): +// generate_token.py example.com Frobulate --is-subdomain +// --expire-timestamp=1458766277 +const char* kSampleSubdomainToken = + "Auu+j9nXAQoy5+t00MiWakZwFExcdNC8ENkRdK1gL4OMFHS0AbZCscslDTcP1fjN" + "FjpbmQG+VCPk1NrldVXZng4AAABoeyJvcmlnaW4iOiAiaHR0cHM6Ly9leGFtcGxl" + "LmNvbTo0NDMiLCAiaXNTdWJkb21haW4iOiB0cnVlLCAiZmVhdHVyZSI6ICJGcm9i" + "dWxhdGUiLCAiZXhwaXJ5IjogMTQ1ODc2NjI3N30="; + +// This is a good trial token, explicitly not a subdomain, signed with the above +// test private key. Generate this token with the command: +// generate_token.py valid.example.com Frobulate --no-subdomain +// --expire-timestamp=1458766277 +const char* kSampleNonSubdomainToken = + "AreD979D7tO0luSZTr1+/+J6E0SSj/GEUyLK41o1hXFzXw1R7Z1hCDHs0gXWVSu1" + "lvH52Winvy39tHbsU2gJJQYAAABveyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiaXNTdWJkb21haW4iOiBmYWxzZSwgImZlYXR1cmUi" + "OiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6IDE0NTg3NjYyNzd9"; + const char* kExpectedFeatureName = "Frobulate"; const char* kExpectedOrigin = "https://valid.example.com"; +const char* kExpectedSubdomainOrigin = "https://example.com"; +const char* kExpectedMultipleSubdomainOrigin = + "https://part1.part2.part3.example.com"; const uint64_t kExpectedExpiry = 1458766277; // The token should not be valid for this origin, or for this feature. const char* kInvalidOrigin = "https://invalid.example.com"; const char* kInsecureOrigin = "http://valid.example.com"; +const char* kIncorrectPortOrigin = "https://valid.example.com:444"; +const char* kIncorrectDomainOrigin = "https://valid.example2.com"; +const char* kInvalidTLDOrigin = "https://com"; const char* kInvalidFeatureName = "Grokalyze"; // The token should be valid if the current time is kValidTimestamp or earlier. @@ -105,6 +138,14 @@ const char kSampleTokenJSON[] = "{\"origin\": \"https://valid.example.com:443\", \"feature\": " "\"Frobulate\", \"expiry\": 1458766277}"; +const char kSampleNonSubdomainTokenJSON[] = + "{\"origin\": \"https://valid.example.com:443\", \"isSubdomain\": false, " + "\"feature\": \"Frobulate\", \"expiry\": 1458766277}"; + +const char kSampleSubdomainTokenJSON[] = + "{\"origin\": \"https://example.com:443\", \"isSubdomain\": true, " + "\"feature\": \"Frobulate\", \"expiry\": 1458766277}"; + // Various ill-formed trial tokens. These should all fail to parse. const char* kInvalidTokens[] = { // Invalid - Not JSON at all @@ -119,13 +160,17 @@ const char* kInvalidTokens[] = { "{}", "{\"something\": 1}", "{\"origin\": \"https://a.a\"}", - "{\"origin\": \"https://a.a\", \"feature\": \"a\"}" + "{\"origin\": \"https://a.a\", \"feature\": \"a\"}", "{\"origin\": \"https://a.a\", \"expiry\": 1458766277}", "{\"feature\": \"FeatureName\", \"expiry\": 1458766277}", // Incorrect types "{\"origin\": 1, \"feature\": \"a\", \"expiry\": 1458766277}", "{\"origin\": \"https://a.a\", \"feature\": 1, \"expiry\": 1458766277}", "{\"origin\": \"https://a.a\", \"feature\": \"a\", \"expiry\": \"1\"}", + "{\"origin\": \"https://a.a\", \"isSubdomain\": \"true\", \"feature\": " + "\"a\", \"expiry\": 1458766277}", + "{\"origin\": \"https://a.a\", \"isSubdomain\": 1, \"feature\": \"a\", " + "\"expiry\": 1458766277}", // Negative expiry timestamp "{\"origin\": \"https://a.a\", \"feature\": \"a\", \"expiry\": -1}", // Origin not a proper origin URL @@ -133,7 +178,8 @@ const char* kInvalidTokens[] = { "{\"origin\": \"data:text/plain,abcdef\", \"feature\": \"a\", \"expiry\": " "1458766277}", "{\"origin\": \"javascript:alert(1)\", \"feature\": \"a\", \"expiry\": " - "1458766277}"}; + "1458766277}", +}; } // namespace @@ -141,8 +187,14 @@ class TrialTokenTest : public testing::TestWithParam<const char*> { public: TrialTokenTest() : expected_origin_(GURL(kExpectedOrigin)), + expected_subdomain_origin_(GURL(kExpectedSubdomainOrigin)), + expected_multiple_subdomain_origin_( + GURL(kExpectedMultipleSubdomainOrigin)), invalid_origin_(GURL(kInvalidOrigin)), insecure_origin_(GURL(kInsecureOrigin)), + incorrect_port_origin_(GURL(kIncorrectPortOrigin)), + incorrect_domain_origin_(GURL(kIncorrectDomainOrigin)), + invalid_tld_origin_(GURL(kInvalidTLDOrigin)), expected_expiry_(base::Time::FromDoubleT(kExpectedExpiry)), valid_timestamp_(base::Time::FromDoubleT(kValidTimestamp)), invalid_timestamp_(base::Time::FromDoubleT(kInvalidTimestamp)), @@ -187,8 +239,13 @@ class TrialTokenTest : public testing::TestWithParam<const char*> { base::StringPiece incorrect_public_key() { return incorrect_public_key_; } const url::Origin expected_origin_; + const url::Origin expected_subdomain_origin_; + const url::Origin expected_multiple_subdomain_origin_; const url::Origin invalid_origin_; const url::Origin insecure_origin_; + const url::Origin incorrect_port_origin_; + const url::Origin incorrect_domain_origin_; + const url::Origin invalid_tld_origin_; const base::Time expected_expiry_; const base::Time valid_timestamp_; @@ -213,6 +270,22 @@ TEST_F(TrialTokenTest, ValidateValidSignature) { EXPECT_STREQ(kSampleTokenJSON, token_payload.c_str()); } +TEST_F(TrialTokenTest, ValidateSubdomainValidSignature) { + std::string token_payload; + blink::WebOriginTrialTokenStatus status = + Extract(kSampleSubdomainToken, correct_public_key(), &token_payload); + ASSERT_EQ(blink::WebOriginTrialTokenStatus::Success, status); + EXPECT_STREQ(kSampleSubdomainTokenJSON, token_payload.c_str()); +} + +TEST_F(TrialTokenTest, ValidateNonSubdomainValidSignature) { + std::string token_payload; + blink::WebOriginTrialTokenStatus status = + Extract(kSampleNonSubdomainToken, correct_public_key(), &token_payload); + ASSERT_EQ(blink::WebOriginTrialTokenStatus::Success, status); + EXPECT_STREQ(kSampleNonSubdomainTokenJSON, token_payload.c_str()); +} + TEST_F(TrialTokenTest, ValidateInvalidSignature) { blink::WebOriginTrialTokenStatus status = ExtractIgnorePayload(kInvalidSignatureToken, correct_public_key()); @@ -267,16 +340,39 @@ TEST_F(TrialTokenTest, ParseValidToken) { std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); EXPECT_EQ(kExpectedFeatureName, token->feature_name()); + EXPECT_FALSE(token->match_subdomains()); + EXPECT_EQ(expected_origin_, token->origin()); + EXPECT_EQ(expected_expiry_, token->expiry_time()); +} + +TEST_F(TrialTokenTest, ParseValidNonSubdomainToken) { + std::unique_ptr<TrialToken> token = Parse(kSampleNonSubdomainTokenJSON); + ASSERT_TRUE(token); + EXPECT_EQ(kExpectedFeatureName, token->feature_name()); + EXPECT_FALSE(token->match_subdomains()); EXPECT_EQ(expected_origin_, token->origin()); EXPECT_EQ(expected_expiry_, token->expiry_time()); } +TEST_F(TrialTokenTest, ParseValidSubdomainToken) { + std::unique_ptr<TrialToken> token = Parse(kSampleSubdomainTokenJSON); + ASSERT_TRUE(token); + EXPECT_EQ(kExpectedFeatureName, token->feature_name()); + EXPECT_TRUE(token->match_subdomains()); + EXPECT_EQ(kExpectedSubdomainOrigin, token->origin().Serialize()); + EXPECT_EQ(expected_subdomain_origin_, token->origin()); + EXPECT_EQ(expected_expiry_, token->expiry_time()); +} + TEST_F(TrialTokenTest, ValidateValidToken) { std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); EXPECT_TRUE(ValidateOrigin(token.get(), expected_origin_)); EXPECT_FALSE(ValidateOrigin(token.get(), invalid_origin_)); EXPECT_FALSE(ValidateOrigin(token.get(), insecure_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), incorrect_port_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), incorrect_domain_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), invalid_tld_origin_)); EXPECT_TRUE(ValidateFeatureName(token.get(), kExpectedFeatureName)); EXPECT_FALSE(ValidateFeatureName(token.get(), kInvalidFeatureName)); EXPECT_FALSE(ValidateFeatureName( @@ -287,32 +383,51 @@ TEST_F(TrialTokenTest, ValidateValidToken) { EXPECT_FALSE(ValidateDate(token.get(), invalid_timestamp_)); } -TEST_F(TrialTokenTest, TokenIsValidForFeature) { +TEST_F(TrialTokenTest, ValidateValidSubdomainToken) { + std::unique_ptr<TrialToken> token = Parse(kSampleSubdomainTokenJSON); + ASSERT_TRUE(token); + EXPECT_TRUE(ValidateOrigin(token.get(), expected_origin_)); + EXPECT_TRUE(ValidateOrigin(token.get(), expected_subdomain_origin_)); + EXPECT_TRUE(ValidateOrigin(token.get(), expected_multiple_subdomain_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), insecure_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), incorrect_port_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), incorrect_domain_origin_)); + EXPECT_FALSE(ValidateOrigin(token.get(), invalid_tld_origin_)); +} + +TEST_F(TrialTokenTest, TokenIsValid) { std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); EXPECT_EQ(blink::WebOriginTrialTokenStatus::Success, - token->IsValidForFeature(expected_origin_, kExpectedFeatureName, - valid_timestamp_)); - EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongFeature, - token->IsValidForFeature(expected_origin_, - base::ToUpperASCII(kExpectedFeatureName), - valid_timestamp_)); - EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongFeature, - token->IsValidForFeature(expected_origin_, - base::ToLowerASCII(kExpectedFeatureName), - valid_timestamp_)); + token->IsValid(expected_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, + token->IsValid(invalid_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, + token->IsValid(insecure_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, + token->IsValid(incorrect_port_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::Expired, + token->IsValid(expected_origin_, invalid_timestamp_)); +} + +TEST_F(TrialTokenTest, SubdomainTokenIsValid) { + std::unique_ptr<TrialToken> token = Parse(kSampleSubdomainTokenJSON); + ASSERT_TRUE(token); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::Success, + token->IsValid(expected_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::Success, + token->IsValid(expected_subdomain_origin_, valid_timestamp_)); + EXPECT_EQ( + blink::WebOriginTrialTokenStatus::Success, + token->IsValid(expected_multiple_subdomain_origin_, valid_timestamp_)); + EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, + token->IsValid(incorrect_domain_origin_, valid_timestamp_)); EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, - token->IsValidForFeature(invalid_origin_, kExpectedFeatureName, - valid_timestamp_)); + token->IsValid(insecure_origin_, valid_timestamp_)); EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, - token->IsValidForFeature(insecure_origin_, kExpectedFeatureName, - valid_timestamp_)); - EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongFeature, - token->IsValidForFeature(expected_origin_, kInvalidFeatureName, - valid_timestamp_)); + token->IsValid(incorrect_port_origin_, valid_timestamp_)); EXPECT_EQ(blink::WebOriginTrialTokenStatus::Expired, - token->IsValidForFeature(expected_origin_, kExpectedFeatureName, - invalid_timestamp_)); + token->IsValid(expected_origin_, invalid_timestamp_)); } // Test overall extraction, to ensure output status matches returned token diff --git a/chromium/content/common/origin_trials/trial_token_validator.cc b/chromium/content/common/origin_trials/trial_token_validator.cc index 3f98ad67e72..34ae30448f2 100644 --- a/chromium/content/common/origin_trials/trial_token_validator.cc +++ b/chromium/content/common/origin_trials/trial_token_validator.cc @@ -4,10 +4,15 @@ #include "content/common/origin_trials/trial_token_validator.h" +#include "base/feature_list.h" #include "base/time/time.h" #include "content/common/origin_trials/trial_token.h" #include "content/public/common/content_client.h" +#include "content/public/common/content_features.h" #include "content/public/common/origin_trial_policy.h" +#include "content/public/common/origin_util.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/url_request.h" #include "third_party/WebKit/public/platform/WebOriginTrialTokenStatus.h" namespace content { @@ -15,32 +20,67 @@ namespace content { blink::WebOriginTrialTokenStatus TrialTokenValidator::ValidateToken( const std::string& token, const url::Origin& origin, - base::StringPiece feature_name) { + std::string* feature_name) { ContentClient* content_client = GetContentClient(); const OriginTrialPolicy* origin_trial_policy = content_client->GetOriginTrialPolicy(); if (!origin_trial_policy) return blink::WebOriginTrialTokenStatus::NotSupported; - if (origin_trial_policy->IsFeatureDisabled(feature_name)) - return blink::WebOriginTrialTokenStatus::FeatureDisabled; - // TODO(iclelland): Allow for multiple signing keys, and iterate over all // active keys here. https://crbug.com/543220 base::StringPiece public_key = origin_trial_policy->GetPublicKey(); - if (public_key.empty()) { + if (public_key.empty()) return blink::WebOriginTrialTokenStatus::NotSupported; - } blink::WebOriginTrialTokenStatus status; std::unique_ptr<TrialToken> trial_token = TrialToken::From(token, public_key, &status); - if (status != blink::WebOriginTrialTokenStatus::Success) { + if (status != blink::WebOriginTrialTokenStatus::Success) return status; - } - return trial_token->IsValidForFeature(origin, feature_name, - base::Time::Now()); + status = trial_token->IsValid(origin, base::Time::Now()); + if (status != blink::WebOriginTrialTokenStatus::Success) + return status; + + if (origin_trial_policy->IsFeatureDisabled(trial_token->feature_name())) + return blink::WebOriginTrialTokenStatus::FeatureDisabled; + + *feature_name = trial_token->feature_name(); + return blink::WebOriginTrialTokenStatus::Success; +} + +bool TrialTokenValidator::RequestEnablesFeature( + const net::URLRequest* request, + base::StringPiece feature_name) { + // TODO(mek): Possibly cache the features that are availble for request in + // UserData associated with the request. + return RequestEnablesFeature(request->url(), request->response_headers(), + feature_name); +} + +bool TrialTokenValidator::RequestEnablesFeature( + const GURL& request_url, + const net::HttpResponseHeaders* response_headers, + base::StringPiece feature_name) { + if (!base::FeatureList::IsEnabled(features::kOriginTrials)) + return false; + + if (!IsOriginSecure(request_url)) + return false; + + url::Origin origin(request_url); + size_t iter = 0; + std::string token; + while (response_headers->EnumerateHeader(&iter, "Origin-Trial", &token)) { + std::string token_feature; + // TODO(mek): Log the validation errors to histograms? + if (ValidateToken(token, origin, &token_feature) == + blink::WebOriginTrialTokenStatus::Success) + if (token_feature == feature_name) + return true; + } + return false; } } // namespace content diff --git a/chromium/content/common/origin_trials/trial_token_validator.h b/chromium/content/common/origin_trials/trial_token_validator.h index 07f99c745ff..1997985cb4e 100644 --- a/chromium/content/common/origin_trials/trial_token_validator.h +++ b/chromium/content/common/origin_trials/trial_token_validator.h @@ -14,14 +14,29 @@ namespace blink { enum class WebOriginTrialTokenStatus; } +namespace net { +class HttpResponseHeaders; +class URLRequest; +} + namespace content { namespace TrialTokenValidator { +// If token validates, |*feature_name| is set to the name of the feature the +// token enables. // This method is thread-safe. CONTENT_EXPORT blink::WebOriginTrialTokenStatus ValidateToken( const std::string& token, const url::Origin& origin, + std::string* feature_name); + +CONTENT_EXPORT bool RequestEnablesFeature(const net::URLRequest* request, + base::StringPiece feature_name); + +CONTENT_EXPORT bool RequestEnablesFeature( + const GURL& request_url, + const net::HttpResponseHeaders* response_headers, base::StringPiece feature_name); } // namespace TrialTokenValidator diff --git a/chromium/content/common/origin_trials/trial_token_validator_unittest.cc b/chromium/content/common/origin_trials/trial_token_validator_unittest.cc index af18d227600..19b5d44c57e 100644 --- a/chromium/content/common/origin_trials/trial_token_validator_unittest.cc +++ b/chromium/content/common/origin_trials/trial_token_validator_unittest.cc @@ -14,6 +14,7 @@ #include "base/time/time.h" #include "content/public/common/content_client.h" #include "content/public/common/origin_trial_policy.h" +#include "net/http/http_response_headers.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebOriginTrialTokenStatus.h" #include "url/gurl.h" @@ -87,6 +88,16 @@ const char kExpiredToken[] = const char kUnparsableToken[] = "abcde"; +// Well-formed token, for an insecure origin. +// Generate this token with the command (in tools/origin_trials): +// generate_token.py http://valid.example.com Frobulate +// --expire-timestamp=2000000000 +const char kInsecureOriginToken[] = + "AjfC47H1q8/Ho5ALFkjkwf9CBK6oUUeRTlFc50Dj+eZEyGGKFIY2WTxMBfy8cLc3" + "E0nmFroDA3OmABmO5jMCFgkAAABXeyJvcmlnaW4iOiAiaHR0cDovL3ZhbGlkLmV4" + "YW1wbGUuY29tOjgwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6" + "IDIwMDAwMDAwMDB9"; + class TestOriginTrialPolicy : public OriginTrialPolicy { public: base::StringPiece GetPublicKey() const override { @@ -133,7 +144,8 @@ class TrialTokenValidatorTest : public testing::Test { TrialTokenValidatorTest() : appropriate_origin_(GURL(kAppropriateOrigin)), inappropriate_origin_(GURL(kInappropriateOrigin)), - insecure_origin_(GURL(kInsecureOrigin)) { + insecure_origin_(GURL(kInsecureOrigin)), + response_headers_(new net::HttpResponseHeaders("")) { SetPublicKey(kTestPublicKey); SetContentClient(&test_content_client_); } @@ -152,69 +164,120 @@ class TrialTokenValidatorTest : public testing::Test { const url::Origin inappropriate_origin_; const url::Origin insecure_origin_; + scoped_refptr<net::HttpResponseHeaders> response_headers_; + private: TestContentClient test_content_client_; }; TEST_F(TrialTokenValidatorTest, ValidateValidToken) { + std::string feature; EXPECT_EQ(blink::WebOriginTrialTokenStatus::Success, - TrialTokenValidator::ValidateToken( - kSampleToken, appropriate_origin_, kAppropriateFeatureName)); + TrialTokenValidator::ValidateToken(kSampleToken, + appropriate_origin_, &feature)); + EXPECT_EQ(kAppropriateFeatureName, feature); } TEST_F(TrialTokenValidatorTest, ValidateInappropriateOrigin) { + std::string feature; EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, TrialTokenValidator::ValidateToken( - kSampleToken, inappropriate_origin_, kAppropriateFeatureName)); + kSampleToken, inappropriate_origin_, &feature)); EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongOrigin, TrialTokenValidator::ValidateToken(kSampleToken, insecure_origin_, - kAppropriateFeatureName)); -} - -TEST_F(TrialTokenValidatorTest, ValidateInappropriateFeature) { - EXPECT_EQ(blink::WebOriginTrialTokenStatus::WrongFeature, - TrialTokenValidator::ValidateToken( - kSampleToken, appropriate_origin_, kInappropriateFeatureName)); + &feature)); } TEST_F(TrialTokenValidatorTest, ValidateInvalidSignature) { + std::string feature; EXPECT_EQ(blink::WebOriginTrialTokenStatus::InvalidSignature, TrialTokenValidator::ValidateToken(kInvalidSignatureToken, - appropriate_origin_, - kAppropriateFeatureName)); + appropriate_origin_, &feature)); } TEST_F(TrialTokenValidatorTest, ValidateUnparsableToken) { + std::string feature; EXPECT_EQ(blink::WebOriginTrialTokenStatus::Malformed, TrialTokenValidator::ValidateToken(kUnparsableToken, - appropriate_origin_, - kAppropriateFeatureName)); + appropriate_origin_, &feature)); } TEST_F(TrialTokenValidatorTest, ValidateExpiredToken) { + std::string feature; EXPECT_EQ(blink::WebOriginTrialTokenStatus::Expired, - TrialTokenValidator::ValidateToken( - kExpiredToken, appropriate_origin_, kAppropriateFeatureName)); + TrialTokenValidator::ValidateToken(kExpiredToken, + appropriate_origin_, &feature)); } TEST_F(TrialTokenValidatorTest, ValidateValidTokenWithIncorrectKey) { + std::string feature; SetPublicKey(kTestPublicKey2); EXPECT_EQ(blink::WebOriginTrialTokenStatus::InvalidSignature, - TrialTokenValidator::ValidateToken( - kSampleToken, appropriate_origin_, kAppropriateFeatureName)); + TrialTokenValidator::ValidateToken(kSampleToken, + appropriate_origin_, &feature)); } TEST_F(TrialTokenValidatorTest, ValidatorRespectsDisabledFeatures) { + std::string feature; // Disable an irrelevant feature; token should still validate DisableFeature(kInappropriateFeatureName); EXPECT_EQ(blink::WebOriginTrialTokenStatus::Success, - TrialTokenValidator::ValidateToken( - kSampleToken, appropriate_origin_, kAppropriateFeatureName)); + TrialTokenValidator::ValidateToken(kSampleToken, + appropriate_origin_, &feature)); + EXPECT_EQ(kAppropriateFeatureName, feature); // Disable the token's feature; it should no longer be valid DisableFeature(kAppropriateFeatureName); EXPECT_EQ(blink::WebOriginTrialTokenStatus::FeatureDisabled, - TrialTokenValidator::ValidateToken( - kSampleToken, appropriate_origin_, kAppropriateFeatureName)); + TrialTokenValidator::ValidateToken(kSampleToken, + appropriate_origin_, &feature)); +} + +TEST_F(TrialTokenValidatorTest, ValidateRequestInsecure) { + response_headers_->AddHeader(std::string("Origin-Trial: ") + + kInsecureOriginToken); + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kInsecureOrigin), response_headers_.get(), kAppropriateFeatureName)); +} + +TEST_F(TrialTokenValidatorTest, ValidateRequestValidToken) { + response_headers_->AddHeader(std::string("Origin-Trial: ") + kSampleToken); + EXPECT_TRUE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); +} + +TEST_F(TrialTokenValidatorTest, ValidateRequestNoTokens) { + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); +} + +TEST_F(TrialTokenValidatorTest, ValidateRequestMultipleHeaders) { + response_headers_->AddHeader(std::string("Origin-Trial: ") + kSampleToken); + response_headers_->AddHeader(std::string("Origin-Trial: ") + kExpiredToken); + EXPECT_TRUE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kInappropriateFeatureName)); + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kInappropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); +} + +TEST_F(TrialTokenValidatorTest, ValidateRequestMultipleHeaderValues) { + response_headers_->AddHeader(std::string("Origin-Trial: ") + kExpiredToken + + ", " + kSampleToken); + EXPECT_TRUE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kAppropriateOrigin), response_headers_.get(), + kInappropriateFeatureName)); + EXPECT_FALSE(TrialTokenValidator::RequestEnablesFeature( + GURL(kInappropriateOrigin), response_headers_.get(), + kAppropriateFeatureName)); } } // namespace content diff --git a/chromium/content/common/origin_util.cc b/chromium/content/common/origin_util.cc index 4dfdc6ce8ca..4af685acc31 100644 --- a/chromium/content/common/origin_util.cc +++ b/chromium/content/common/origin_util.cc @@ -4,12 +4,17 @@ #include "content/public/common/origin_util.h" +#include <string> + #include "base/lazy_instance.h" #include "base/macros.h" #include "base/stl_util.h" +#include "base/strings/string_piece.h" #include "content/public/common/content_client.h" +#include "content/public/common/url_constants.h" #include "net/base/url_util.h" #include "url/gurl.h" +#include "url/url_constants.h" namespace content { @@ -21,6 +26,9 @@ class SchemeAndOriginWhitelist { ~SchemeAndOriginWhitelist() {} void Reset() { + secure_schemes_.clear(); + secure_origins_.clear(); + service_worker_schemes_.clear(); GetContentClient()->AddSecureSchemesAndOrigins(&secure_schemes_, &secure_origins_); GetContentClient()->AddServiceWorkerSchemes(&service_worker_schemes_); @@ -59,11 +67,12 @@ bool IsOriginSecure(const GURL& url) { if (net::IsLocalhost(hostname)) return true; - if (ContainsKey(g_trustworthy_whitelist.Get().secure_schemes(), url.scheme())) + if (base::ContainsKey(g_trustworthy_whitelist.Get().secure_schemes(), + url.scheme())) return true; - if (ContainsKey(g_trustworthy_whitelist.Get().secure_origins(), - url.GetOrigin())) { + if (base::ContainsKey(g_trustworthy_whitelist.Get().secure_origins(), + url.GetOrigin())) { return true; } @@ -74,8 +83,8 @@ bool OriginCanAccessServiceWorkers(const GURL& url) { if (url.SchemeIsHTTPOrHTTPS() && IsOriginSecure(url)) return true; - if (ContainsKey(g_trustworthy_whitelist.Get().service_worker_schemes(), - url.scheme())) { + if (base::ContainsKey(g_trustworthy_whitelist.Get().service_worker_schemes(), + url.scheme())) { return true; } @@ -86,4 +95,63 @@ void ResetSchemesAndOriginsWhitelistForTesting() { g_trustworthy_whitelist.Get().Reset(); } +bool HasSuborigin(const GURL& url) { + if (!url.is_valid()) + return false; + + if (url.scheme() != kHttpSuboriginScheme && + url.scheme() != kHttpsSuboriginScheme) { + return false; + } + + base::StringPiece host_piece = url.host_piece(); + size_t first_period = host_piece.find('.'); + + // If the first period is the first position in the hostname, or there is no + // period at all, there is no suborigin serialized in the hostname. + if (first_period == 0 || first_period == base::StringPiece::npos) + return false; + + // If there's nothing after the first dot, then there is no host for the + // physical origin, which is not a valid suborigin serialization. + if (first_period == (host_piece.size() - 1)) + return false; + + return true; +} + +std::string SuboriginFromUrl(const GURL& url) { + if (!HasSuborigin(url)) + return ""; + + std::string host = url.host(); + size_t suborigin_end = host.find("."); + return (suborigin_end == std::string::npos) ? "" + : host.substr(0, suborigin_end); +} + +GURL StripSuboriginFromUrl(const GURL& url) { + if (!HasSuborigin(url)) + return url; + + GURL::Replacements replacements; + if (url.scheme() == kHttpSuboriginScheme) { + replacements.SetSchemeStr(url::kHttpScheme); + } else { + DCHECK(url.scheme() == kHttpsSuboriginScheme); + replacements.SetSchemeStr(url::kHttpsScheme); + } + + std::string host = url.host(); + size_t suborigin_end = host.find("."); + std::string new_host( + (suborigin_end == std::string::npos) + ? "" + : host.substr(suborigin_end + 1, + url.host().length() - suborigin_end - 1)); + replacements.SetHostStr(new_host); + + return url.ReplaceComponents(replacements); +} + } // namespace content diff --git a/chromium/content/common/origin_util_unittest.cc b/chromium/content/common/origin_util_unittest.cc index 3c2328bff99..d4409a01f01 100644 --- a/chromium/content/common/origin_util_unittest.cc +++ b/chromium/content/common/origin_util_unittest.cc @@ -47,4 +47,81 @@ TEST(URLSchemesTest, IsOriginSecure) { IsOriginSecure(GURL("filesystem:https://www.example.com/temporary/"))); } +TEST(OriginUtilTest, Suborigins) { + GURL no_suborigin_simple_url("https://b"); + GURL suborigin_simple_url("https-so://a.b"); + GURL no_suborigin_path_url("https://example.com/some/path"); + GURL suborigin_path_url("https-so://foobar.example.com/some/path"); + GURL no_suborigin_url_with_port("https://example.com:1234"); + GURL suborigin_url_with_port("https-so://foobar.example.com:1234"); + GURL no_suborigin_url_with_query("https://example.com/some/path?query"); + GURL suborigin_url_with_query( + "https-so://foobar.example.com/some/path?query"); + GURL no_suborigin_url_with_fragment("https://example.com/some/path#fragment"); + GURL suborigin_url_with_fragment( + "https-so://foobar.example.com/some/path#fragment"); + GURL no_suborigin_url_big( + "https://example.com:1234/some/path?query#fragment"); + GURL suborigin_url_big( + "https-so://foobar.example.com:1234/some/path?query#fragment"); + + EXPECT_FALSE(HasSuborigin(no_suborigin_simple_url)); + EXPECT_FALSE(HasSuborigin(no_suborigin_path_url)); + EXPECT_TRUE(HasSuborigin(suborigin_simple_url)); + EXPECT_TRUE(HasSuborigin(suborigin_path_url)); + EXPECT_TRUE(HasSuborigin(suborigin_url_with_port)); + EXPECT_TRUE(HasSuborigin(suborigin_url_with_query)); + EXPECT_TRUE(HasSuborigin(suborigin_url_with_fragment)); + EXPECT_TRUE(HasSuborigin(suborigin_url_big)); + + EXPECT_EQ("", SuboriginFromUrl(no_suborigin_simple_url)); + EXPECT_EQ("", SuboriginFromUrl(no_suborigin_path_url)); + EXPECT_EQ("a", SuboriginFromUrl(suborigin_simple_url)); + EXPECT_EQ("foobar", SuboriginFromUrl(suborigin_path_url)); + EXPECT_EQ("foobar", SuboriginFromUrl(suborigin_url_with_port)); + EXPECT_EQ("foobar", SuboriginFromUrl(suborigin_url_with_query)); + EXPECT_EQ("foobar", SuboriginFromUrl(suborigin_url_with_fragment)); + EXPECT_EQ("foobar", SuboriginFromUrl(suborigin_url_big)); + + EXPECT_EQ(no_suborigin_simple_url, + StripSuboriginFromUrl(no_suborigin_simple_url)); + EXPECT_EQ(no_suborigin_path_url, + StripSuboriginFromUrl(no_suborigin_path_url)); + EXPECT_EQ(no_suborigin_simple_url, + StripSuboriginFromUrl(suborigin_simple_url)); + EXPECT_EQ(no_suborigin_path_url, StripSuboriginFromUrl(suborigin_path_url)); + EXPECT_EQ(no_suborigin_url_with_port, + StripSuboriginFromUrl(suborigin_url_with_port)); + EXPECT_EQ(no_suborigin_url_with_query, + StripSuboriginFromUrl(suborigin_url_with_query)); + EXPECT_EQ(no_suborigin_url_with_fragment, + StripSuboriginFromUrl(suborigin_url_with_fragment)); + EXPECT_EQ(no_suborigin_url_big, StripSuboriginFromUrl(suborigin_url_big)); + + // Failure cases/invalid suborigins + GURL just_dot_url("https-so://."); + GURL empty_hostname_url("https-so://"); + GURL empty_suborigin_url("https-so://.foo"); + GURL no_dot_url("https-so://foo"); + GURL suborigin_but_empty_host_url("https-so://foo."); + EXPECT_FALSE(HasSuborigin(just_dot_url)); + EXPECT_FALSE(HasSuborigin(empty_hostname_url)); + EXPECT_FALSE(HasSuborigin(empty_suborigin_url)); + EXPECT_FALSE(HasSuborigin(no_dot_url)); + EXPECT_FALSE(HasSuborigin(suborigin_but_empty_host_url)); + + EXPECT_EQ("", SuboriginFromUrl(just_dot_url)); + EXPECT_EQ("", SuboriginFromUrl(empty_hostname_url)); + EXPECT_EQ("", SuboriginFromUrl(empty_suborigin_url)); + EXPECT_EQ("", SuboriginFromUrl(no_dot_url)); + EXPECT_EQ("", SuboriginFromUrl(suborigin_but_empty_host_url)); + + EXPECT_EQ(just_dot_url, StripSuboriginFromUrl(just_dot_url)); + EXPECT_EQ(empty_hostname_url, StripSuboriginFromUrl(empty_hostname_url)); + EXPECT_EQ(empty_suborigin_url, StripSuboriginFromUrl(empty_suborigin_url)); + EXPECT_EQ(no_dot_url, StripSuboriginFromUrl(no_dot_url)); + EXPECT_EQ(suborigin_but_empty_host_url, + StripSuboriginFromUrl(suborigin_but_empty_host_url)); +} + } // namespace content diff --git a/chromium/content/common/p2p_messages.h b/chromium/content/common/p2p_messages.h index 9725b257cff..51b01447dcf 100644 --- a/chromium/content/common/p2p_messages.h +++ b/chromium/content/common/p2p_messages.h @@ -59,6 +59,11 @@ IPC_STRUCT_TRAITS_BEGIN(content::P2PSendPacketMetrics) IPC_STRUCT_TRAITS_MEMBER(send_time) IPC_STRUCT_TRAITS_END() +IPC_STRUCT_TRAITS_BEGIN(content::P2PPortRange) + IPC_STRUCT_TRAITS_MEMBER(min_port) + IPC_STRUCT_TRAITS_MEMBER(max_port) +IPC_STRUCT_TRAITS_END() + // P2P Socket messages sent from the browser to the renderer. IPC_MESSAGE_CONTROL3(P2PMsg_NetworkListChanged, @@ -104,10 +109,11 @@ IPC_MESSAGE_CONTROL2(P2PHostMsg_GetHostAddress, std::string /* host_name */, int32_t /* request_id */) -IPC_MESSAGE_CONTROL4(P2PHostMsg_CreateSocket, +IPC_MESSAGE_CONTROL5(P2PHostMsg_CreateSocket, content::P2PSocketType /* type */, int /* socket_id */, net::IPEndPoint /* local_address */, + content::P2PPortRange /* port_range */, content::P2PHostAndIPEndPoint /* remote_address */) IPC_MESSAGE_CONTROL3(P2PHostMsg_AcceptIncomingTcpConnection, diff --git a/chromium/content/common/p2p_socket_type.h b/chromium/content/common/p2p_socket_type.h index 0de0e20acdd..d8d21727489 100644 --- a/chromium/content/common/p2p_socket_type.h +++ b/chromium/content/common/p2p_socket_type.h @@ -70,6 +70,18 @@ struct P2PSendPacketMetrics { base::TimeTicks send_time; }; +// Struct that carries a port range. +struct P2PPortRange { + P2PPortRange() : P2PPortRange(0, 0) {} + P2PPortRange(uint16_t min_port, uint16_t max_port) + : min_port(min_port), max_port(max_port) { + DCHECK_LE(min_port, max_port); + DCHECK((min_port == 0 && max_port == 0) || min_port > 0); + } + uint16_t min_port; + uint16_t max_port; +}; + } // namespace content #endif // CONTENT_COMMON_P2P_SOCKET_TYPE_H_ diff --git a/chromium/content/common/page_messages.h b/chromium/content/common/page_messages.h index 77aa978ce9c..6b988a352d4 100644 --- a/chromium/content/common/page_messages.h +++ b/chromium/content/common/page_messages.h @@ -27,12 +27,22 @@ IPC_MESSAGE_ROUTED2(PageMsg_SetZoomLevel, PageMsg_SetZoomLevel_Command /* command */, double /* zoom_level */) +IPC_MESSAGE_ROUTED1(PageMsg_SetDeviceScaleFactor, + double /* device_scale_factor */) + // Informs the renderer that the page was hidden. IPC_MESSAGE_ROUTED0(PageMsg_WasHidden) // Informs the renderer that the page is no longer hidden. IPC_MESSAGE_ROUTED0(PageMsg_WasShown) +// Sent when the history for this page is altered from another process. The +// history list should be reset to |history_length| length, and the offset +// should be reset to |history_offset|. +IPC_MESSAGE_ROUTED2(PageMsg_SetHistoryOffsetAndLength, + int /* history_offset */, + int /* history_length */) + // ----------------------------------------------------------------------------- // Messages sent from the renderer to the browser. diff --git a/chromium/content/common/page_state_serialization.cc b/chromium/content/common/page_state_serialization.cc index 7a917d6f394..2d4782e27b6 100644 --- a/chromium/content/common/page_state_serialization.cc +++ b/chromium/content/common/page_state_serialization.cc @@ -514,7 +514,7 @@ void WriteFrameState( WriteReal(state.page_scale_factor, obj); WriteInteger64(state.item_sequence_number, obj); WriteInteger64(state.document_sequence_number, obj); - WriteInteger(state.referrer_policy, obj); + WriteInteger(static_cast<int>(state.referrer_policy), obj); WriteReal(state.visual_viewport_scroll_offset.x(), obj); WriteReal(state.visual_viewport_scroll_offset.y(), obj); @@ -741,12 +741,11 @@ bool DecodePageState(const std::string& encoded, ExplodedPageState* exploded) { return !obj.parse_error; } -bool EncodePageState(const ExplodedPageState& exploded, std::string* encoded) { +void EncodePageState(const ExplodedPageState& exploded, std::string* encoded) { SerializeObject obj; obj.version = kCurrentVersion; WritePageState(exploded, &obj); *encoded = obj.GetAsString(); - return true; } #if defined(OS_ANDROID) diff --git a/chromium/content/common/page_state_serialization.h b/chromium/content/common/page_state_serialization.h index 90484c4387b..51ad47a49b8 100644 --- a/chromium/content/common/page_state_serialization.h +++ b/chromium/content/common/page_state_serialization.h @@ -71,7 +71,7 @@ struct CONTENT_EXPORT ExplodedPageState { CONTENT_EXPORT bool DecodePageState(const std::string& encoded, ExplodedPageState* exploded); -CONTENT_EXPORT bool EncodePageState(const ExplodedPageState& exploded, +CONTENT_EXPORT void EncodePageState(const ExplodedPageState& exploded, std::string* encoded); #if defined(OS_ANDROID) diff --git a/chromium/content/common/page_state_serialization_unittest.cc b/chromium/content/common/page_state_serialization_unittest.cc index 99039f2a7f7..9ed9d33ed04 100644 --- a/chromium/content/common/page_state_serialization_unittest.cc +++ b/chromium/content/common/page_state_serialization_unittest.cc @@ -241,7 +241,7 @@ TEST_F(PageStateSerializationTest, BasicEmpty) { ExplodedPageState input; std::string encoded; - EXPECT_TRUE(EncodePageState(input, &encoded)); + EncodePageState(input, &encoded); ExplodedPageState output; EXPECT_TRUE(DecodePageState(encoded, &output)); @@ -254,7 +254,7 @@ TEST_F(PageStateSerializationTest, BasicFrame) { PopulateFrameState(&input.top); std::string encoded; - EXPECT_TRUE(EncodePageState(input, &encoded)); + EncodePageState(input, &encoded); ExplodedPageState output; EXPECT_TRUE(DecodePageState(encoded, &output)); @@ -268,7 +268,7 @@ TEST_F(PageStateSerializationTest, BasicFramePOST) { PopulateHttpBody(&input.top.http_body, &input.referenced_files); std::string encoded; - EXPECT_TRUE(EncodePageState(input, &encoded)); + EncodePageState(input, &encoded); ExplodedPageState output; EXPECT_TRUE(DecodePageState(encoded, &output)); @@ -288,7 +288,7 @@ TEST_F(PageStateSerializationTest, BasicFrameSet) { } std::string encoded; - EXPECT_TRUE(EncodePageState(input, &encoded)); + EncodePageState(input, &encoded); ExplodedPageState output; EXPECT_TRUE(DecodePageState(encoded, &output)); @@ -371,7 +371,7 @@ TEST_F(PageStateSerializationTest, DumpExpectedPageStateForBackwardsCompat) { PopulatePageStateForBackwardsCompatTest(&state); std::string encoded; - EXPECT_TRUE(EncodePageState(state, &encoded)); + EncodePageState(state, &encoded); std::string base64; base::Base64Encode(encoded, &base64); diff --git a/chromium/content/common/platform_notification_messages.h b/chromium/content/common/platform_notification_messages.h index 7f27b8b4168..02bb9f3af97 100644 --- a/chromium/content/common/platform_notification_messages.h +++ b/chromium/content/common/platform_notification_messages.h @@ -19,10 +19,10 @@ #ifndef CONTENT_COMMON_PLATFORM_NOTIFICATION_MESSAGES_H_ #define CONTENT_COMMON_PLATFORM_NOTIFICATION_MESSAGES_H_ -// Defines the pair of [persistent notification id] => [notification data] used -// when getting the notifications for a given Service Worker registration. +// Defines the pair of [notification id] => [notification data] used when +// getting the notifications for a given Service Worker registration. using PersistentNotificationInfo = - std::pair<int64_t, content::PlatformNotificationData>; + std::pair<std::string, content::PlatformNotificationData>; #endif // CONTENT_COMMON_PLATFORM_NOTIFICATION_MESSAGES_H_ @@ -49,6 +49,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::PlatformNotificationData) IPC_STRUCT_TRAITS_MEMBER(lang) IPC_STRUCT_TRAITS_MEMBER(body) IPC_STRUCT_TRAITS_MEMBER(tag) + IPC_STRUCT_TRAITS_MEMBER(image) IPC_STRUCT_TRAITS_MEMBER(icon) IPC_STRUCT_TRAITS_MEMBER(badge) IPC_STRUCT_TRAITS_MEMBER(vibration_pattern) @@ -61,6 +62,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::PlatformNotificationData) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::NotificationResources) + IPC_STRUCT_TRAITS_MEMBER(image) IPC_STRUCT_TRAITS_MEMBER(notification_icon) IPC_STRUCT_TRAITS_MEMBER(badge) IPC_STRUCT_TRAITS_MEMBER(action_icons) @@ -98,7 +100,7 @@ IPC_MESSAGE_CONTROL2(PlatformNotificationMsg_DidGetNotifications, IPC_MESSAGE_CONTROL4( PlatformNotificationHostMsg_Show, - int /* notification_id */, + int /* non_persistent_notification_id */, GURL /* origin */, content::PlatformNotificationData /* notification_data */, content::NotificationResources /* notification_resources */) @@ -117,9 +119,12 @@ IPC_MESSAGE_CONTROL4(PlatformNotificationHostMsg_GetNotifications, GURL /* origin */, std::string /* filter_tag */) -IPC_MESSAGE_CONTROL1(PlatformNotificationHostMsg_Close, - int /* notification_id */) +IPC_MESSAGE_CONTROL3(PlatformNotificationHostMsg_Close, + GURL /* origin */, + std::string /* tag */, + int /* non_persistent_notification_id */) -IPC_MESSAGE_CONTROL2(PlatformNotificationHostMsg_ClosePersistent, +IPC_MESSAGE_CONTROL3(PlatformNotificationHostMsg_ClosePersistent, GURL /* origin */, - int64_t /* persistent_notification_id */) + std::string /* tag */, + std::string /* notification_id */) diff --git a/chromium/content/common/process_control.mojom b/chromium/content/common/process_control.mojom deleted file mode 100644 index d872d81b555..00000000000 --- a/chromium/content/common/process_control.mojom +++ /dev/null @@ -1,13 +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. - -module content.mojom; - -import "services/shell/public/interfaces/shell_client.mojom"; - -interface ProcessControl { - LoadApplication(string url, - shell.mojom.ShellClient& request) => (bool success); -}; - diff --git a/chromium/content/common/push_messaging_messages.h b/chromium/content/common/push_messaging_messages.h index f3710684a3d..5e1caf421a6 100644 --- a/chromium/content/common/push_messaging_messages.h +++ b/chromium/content/common/push_messaging_messages.h @@ -37,15 +37,17 @@ IPC_STRUCT_TRAITS_END() // Messages sent from the browser to the child process. -IPC_MESSAGE_ROUTED4(PushMessagingMsg_SubscribeFromDocumentSuccess, +IPC_MESSAGE_ROUTED5(PushMessagingMsg_SubscribeFromDocumentSuccess, int32_t /* request_id */, GURL /* push_endpoint */, + content::PushSubscriptionOptions /* options */, std::vector<uint8_t> /* p256dh */, std::vector<uint8_t> /* auth */) -IPC_MESSAGE_CONTROL4(PushMessagingMsg_SubscribeFromWorkerSuccess, +IPC_MESSAGE_CONTROL5(PushMessagingMsg_SubscribeFromWorkerSuccess, int32_t /* request_id */, GURL /* push_endpoint */, + content::PushSubscriptionOptions /* options */, std::vector<uint8_t> /* p256dh */, std::vector<uint8_t> /* auth */) @@ -66,9 +68,10 @@ IPC_MESSAGE_CONTROL3(PushMessagingMsg_UnsubscribeError, blink::WebPushError::ErrorType /* error_type */, std::string /* error_message */) -IPC_MESSAGE_CONTROL4(PushMessagingMsg_GetSubscriptionSuccess, +IPC_MESSAGE_CONTROL5(PushMessagingMsg_GetSubscriptionSuccess, int32_t /* request_id */, GURL /* push_endpoint */, + content::PushSubscriptionOptions /* options */, std::vector<uint8_t> /* p256dh */, std::vector<uint8_t> /* auth */) diff --git a/chromium/content/common/render_frame_message_filter.mojom b/chromium/content/common/render_frame_message_filter.mojom new file mode 100644 index 00000000000..5bbf05eaf5f --- /dev/null +++ b/chromium/content/common/render_frame_message_filter.mojom @@ -0,0 +1,20 @@ +// 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. + +module content.mojom; + +import "url/mojo/url.mojom"; + +interface RenderFrameMessageFilter { + // Sets a cookie. The cookie is set asynchronously, but will be available to + // any subsequent GetCookies() request. + SetCookie(int32 render_frame_id, url.mojom.Url url, + url.mojom.Url first_party_for_cookies, string cookie); + + // Used to get cookies for the given URL. This may block waiting for a + // previous SetCookie message to be processed. + [Sync] + GetCookies(int32 render_frame_id, url.mojom.Url url, + url.mojom.Url first_party_for_cookies) => (string cookies); +}; diff --git a/chromium/content/common/render_message_filter.mojom b/chromium/content/common/render_message_filter.mojom new file mode 100644 index 00000000000..3b19f688afe --- /dev/null +++ b/chromium/content/common/render_message_filter.mojom @@ -0,0 +1,85 @@ +// 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. + +module content.mojom; + +import "content/public/common/window_container_type.mojom"; +import "third_party/WebKit/public/platform/referrer.mojom"; +import "third_party/WebKit/public/web/window_features.mojom"; +import "ui/base/mojo/window_open_disposition.mojom"; +import "url/mojo/url.mojom"; + +struct CreateNewWindowParams { + // Routing ID of the view initiating the open. + int32 opener_id; + + // True if this open request came in the context of a user gesture. + bool user_gesture; + + // Type of window requested. + WindowContainerType window_container_type; + + // The session storage namespace ID this view should use. + int64 session_storage_namespace_id; + + // The name of the resulting frame that should be created (empty if none + // has been specified). UTF8 encoded string. + string frame_name; + + // The routing id of the frame initiating the open. + int32 opener_render_frame_id; + + // The URL of the frame initiating the open. + url.mojom.Url opener_url; + + // The URL of the top frame containing the opener. + url.mojom.Url opener_top_level_frame_url; + + // The security origin of the frame initiating the open. + url.mojom.Url opener_security_origin; + + // Whether the opener will be suppressed in the new window, in which case + // scripting the new window is not allowed. + bool opener_suppressed; + + // Whether the window should be opened in the foreground, background, etc. + ui.mojom.WindowOpenDisposition disposition; + + // The URL that will be loaded in the new window (empty if none has been + // sepcified). + url.mojom.Url target_url; + + // The referrer that will be used to load |target_url| (empty if none has + // been specified). + blink.mojom.Referrer referrer; + + // The window features to use for the new view. + blink.mojom.WindowFeatures features; +}; + +struct CreateNewWindowReply { + // The ID of the view to be created. If the ID is MSG_ROUTING_NONE, then the + // view couldn't be created. + int32 route_id; + + // The ID of the main frame hosted in the view. + int32 main_frame_route_id; + + // The ID of the widget for the main frame. + int32 main_frame_widget_route_id; + + // Duplicated from CreateNewWindowParams because legacy code. + int64 cloned_session_storage_namespace_id; +}; + +interface RenderMessageFilter { + // Synchronously generates a new routing ID for the caller. + [Sync] GenerateRoutingID() => (int32 routing_id); + + // Sent by the renderer when it is creating a new window. The browser creates + // a tab for it. If |reply.route_id| is MSG_ROUTING_NONE, the view couldn't + // be created. + [Sync] CreateNewWindow(CreateNewWindowParams params) + => (CreateNewWindowReply reply); +}; diff --git a/chromium/content/common/render_process_messages.h b/chromium/content/common/render_process_messages.h index d72a2b3d14c..77bd8def9b5 100644 --- a/chromium/content/common/render_process_messages.h +++ b/chromium/content/common/render_process_messages.h @@ -77,11 +77,4 @@ IPC_SYNC_MESSAGE_CONTROL1_3(RenderProcessHostMsg_LoadFont, uint32_t /* buffer size */, base::SharedMemoryHandle /* font data */, uint32_t /* font id */) -#elif defined(OS_WIN) -// Request that the given font characters be loaded by the browser so it's -// cached by the OS. Please see RenderMessageFilter::OnPreCacheFontCharacters -// for details. -IPC_SYNC_MESSAGE_CONTROL2_0(RenderProcessHostMsg_PreCacheFontCharacters, - LOGFONT /* font_data */, - base::string16 /* characters */) #endif 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 e6d88d7bfcd..9a375cf499c 100644 --- a/chromium/content/common/render_widget_window_tree_client_factory.mojom +++ b/chromium/content/common/render_widget_window_tree_client_factory.mojom @@ -4,10 +4,10 @@ module content.mojom; -import "components/mus/public/interfaces/window_tree.mojom"; +import "services/ui/public/interfaces/window_tree.mojom"; interface RenderWidgetWindowTreeClientFactory { CreateWindowTreeClientForRenderWidget( uint32 routing_id, - mus.mojom.WindowTreeClient& window_tree_client); + ui.mojom.WindowTreeClient& window_tree_client); }; diff --git a/chromium/content/common/renderer.mojom b/chromium/content/common/renderer.mojom new file mode 100644 index 00000000000..80b1f2f4a4d --- /dev/null +++ b/chromium/content/common/renderer.mojom @@ -0,0 +1,151 @@ +// 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. + +module content.mojom; + +import "content/common/native_types.mojom"; +import "ipc/ipc.mojom"; +import "ui/gfx/geometry/mojo/geometry.mojom"; +import "ui/gfx/mojo/icc_profile.mojom"; + +struct CreateViewParams { + // Renderer-wide preferences. + RendererPreferences renderer_preferences; + + // Preferences for this view. + WebPreferences web_preferences; + + // The ID of the view to be created. + int32 view_id = IPC.mojom.kRoutingIdNone; + + // The ID of the main frame hosted in the view. + int32 main_frame_routing_id = IPC.mojom.kRoutingIdNone; + + // The ID of the widget for the main frame. + int32 main_frame_widget_routing_id = IPC.mojom.kRoutingIdNone; + + // The session storage namespace ID this view should use. + int64 session_storage_namespace_id; + + // The route ID of the opener RenderFrame or RenderFrameProxy, if we need to + // set one (MSG_ROUTING_NONE otherwise). + int32 opener_frame_route_id = IPC.mojom.kRoutingIdNone; + + // Whether the RenderView should initially be swapped out. + bool swapped_out; + + // Carries replicated information, such as frame name and sandbox flags, for + // this view's main frame, which will be a proxy in |swapped_out| + // views when in --site-per-process mode, or a RenderFrame in all other + // cases. + FrameReplicationState replicated_frame_state; + + // The ID of the proxy object for the main frame in this view. It is only + // used if |swapped_out| is true. + int32 proxy_routing_id = IPC.mojom.kRoutingIdNone; + + // Whether the RenderView should initially be hidden. + bool hidden; + + // Whether the RenderView will never be visible. + bool never_visible; + + // Whether the window associated with this view was created with an opener. + bool window_was_created_with_opener; + + // The initial page ID to use for this view, which must be larger than any + // existing navigation that might be loaded in the view. Page IDs are unique + // to a view and are only updated by the renderer after this initial value. + int32 next_page_id; + + // The initial renderer size. + ResizeParams initial_size; + + // Whether to enable auto-resize. + bool enable_auto_resize; + + // The minimum size to layout the page if auto-resize is enabled. + gfx.mojom.Size min_size; + + // The maximum size to layout the page if auto-resize is enabled. + gfx.mojom.Size max_size; + + // The page zoom level. + double page_zoom_level; + + // The ICC profile of the output color space to use for image decode. + gfx.mojom.ICCProfile image_decode_color_space; +}; + +struct CreateFrameWidgetParams { + // Gives the routing ID for the RenderWidget that will be attached to the + // new RenderFrame. If the RenderFrame does not need a RenderWidget, this + // is MSG_ROUTING_NONE and the other parameters are not read. + int32 routing_id; + + // Tells the new RenderWidget whether it is initially hidden. + bool hidden; +}; + +struct CreateFrameParams { + // Specifies the routing ID of the new RenderFrame object. + int32 routing_id; + + // If a valid |proxy_routing_id| is provided, the new frame will be + // configured to replace the proxy on commit. + int32 proxy_routing_id; + + // Specifies the new frame's opener. The opener will be null if this is + // MSG_ROUTING_NONE. + int32 opener_routing_id; + + // The new frame should be created as a child of the object + // identified by |parent_routing_id| or as top level if that is + // MSG_ROUTING_NONE. + int32 parent_routing_id; + + // Identifies the previous sibling of the new frame, so that the new frame is + // inserted into the correct place in the frame tree. If this is + // MSG_ROUTING_NONE, the frame will be created as the leftmost child of its + // parent frame, in front of any other children. + int32 previous_sibling_routing_id; + + // When the new frame has a parent, |replication_state| holds the new frame's + // properties replicated from the process rendering the parent frame, such as + // the new frame's sandbox flags. + FrameReplicationState replication_state; + + // When the new frame has a parent, |frame_owner_properties| holds the + // properties of the HTMLFrameOwnerElement from the parent process. + // Note that unlike FrameReplicationState, this is not replicated for remote + // frames. + FrameOwnerProperties frame_owner_properties; + + // Specifies properties for a new RenderWidget that will be attached to the + // new RenderFrame (if one is needed). + CreateFrameWidgetParams widget_params; +}; + + +// The primordial Channel-associated interface implemented by a render process. +// This should be used for implementing browser-to-renderer control messages +// which need to retain FIFO with respect to legacy IPC messages. +interface Renderer { + // Tells the renderer to create a new view. + CreateView(CreateViewParams params); + + // Tells the renderer to create a new RenderFrame. + CreateFrame(CreateFrameParams params); + + // Tells the renderer to create a new RenderFrameProxy object with + // |routing_id|. |render_view_routing_id| identifies the + // RenderView to be associated with this proxy. The new proxy's opener should + // be set to the object identified by |opener_routing_id|, or to null if that + // is MSG_ROUTING_NONE. The new proxy should be created as a child of the + // object identified by |parent_routing_id| or as top level if that is + // MSG_ROUTING_NONE. + CreateFrameProxy(int32 routing_id, int32 render_view_routing_id, + int32 opener_routing_id, int32 parent_routing_id, + FrameReplicationState replication_state); +}; diff --git a/chromium/content/common/resize_params.cc b/chromium/content/common/resize_params.cc index ea9f18fb65b..ee6943fc77b 100644 --- a/chromium/content/common/resize_params.cc +++ b/chromium/content/common/resize_params.cc @@ -9,6 +9,7 @@ namespace content { ResizeParams::ResizeParams() : top_controls_shrink_blink_size(false), top_controls_height(0.f), + bottom_controls_height(0.f), is_fullscreen_granted(false), display_mode(blink::WebDisplayModeUndefined), needs_resize_ack(false) {} diff --git a/chromium/content/common/resize_params.h b/chromium/content/common/resize_params.h index f9eb07c247d..436cb562b94 100644 --- a/chromium/content/common/resize_params.h +++ b/chromium/content/common/resize_params.h @@ -6,8 +6,8 @@ #define CONTENT_COMMON_RESIZE_PARAMS_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/WebKit/public/platform/WebScreenInfo.h" #include "ui/gfx/geometry/size.h" namespace content { @@ -18,7 +18,7 @@ struct CONTENT_EXPORT ResizeParams { ~ResizeParams(); // Information about the screen (dpi, depth, etc..). - blink::WebScreenInfo screen_info; + ScreenInfo screen_info; // The size of the renderer. gfx::Size new_size; @@ -34,6 +34,9 @@ struct CONTENT_EXPORT ResizeParams { // isn't supported). float top_controls_height; + // The height of the bottom controls. + float bottom_controls_height; + // The size of the visible viewport, which may be smaller than the view if the // view is partially occluded (e.g. by a virtual keyboard). The size is in // DPI-adjusted pixels. diff --git a/chromium/content/common/resource_messages.cc b/chromium/content/common/resource_messages.cc index 3b738693c74..31330a7e208 100644 --- a/chromium/content/common/resource_messages.cc +++ b/chromium/content/common/resource_messages.cc @@ -145,14 +145,14 @@ bool ParamTraits<storage::DataElement>::Read(const base::Pickle* m, if (!iter->ReadData(&data, &len)) return false; r->SetToBytes(data, len); - break; + return true; } case storage::DataElement::TYPE_BYTES_DESCRIPTION: { uint64_t length; if (!ReadParam(m, iter, &length)) return false; r->SetToBytesDescription(length); - break; + return true; } case storage::DataElement::TYPE_FILE: { base::FilePath file_path; @@ -168,7 +168,7 @@ bool ParamTraits<storage::DataElement>::Read(const base::Pickle* m, return false; r->SetToFilePathRange(file_path, offset, length, expected_modification_time); - break; + return true; } case storage::DataElement::TYPE_FILE_FILESYSTEM: { GURL file_system_url; @@ -184,7 +184,7 @@ bool ParamTraits<storage::DataElement>::Read(const base::Pickle* m, return false; r->SetToFileSystemUrlRange(file_system_url, offset, length, expected_modification_time); - break; + return true; } case storage::DataElement::TYPE_BLOB: { std::string blob_uuid; @@ -196,18 +196,18 @@ bool ParamTraits<storage::DataElement>::Read(const base::Pickle* m, if (!ReadParam(m, iter, &length)) return false; r->SetToBlobRange(blob_uuid, offset, length); - break; + return true; } case storage::DataElement::TYPE_DISK_CACHE_ENTRY: { NOTREACHED() << "Can't be sent by IPC."; - break; + return false; } case storage::DataElement::TYPE_UNKNOWN: { NOTREACHED(); - break; + return false; } } - return true; + return false; } void ParamTraits<storage::DataElement>::Log(const param_type& p, diff --git a/chromium/content/common/resource_messages.h b/chromium/content/common/resource_messages.h index 0f343e72c8c..6812be78ea8 100644 --- a/chromium/content/common/resource_messages.h +++ b/chromium/content/common/resource_messages.h @@ -23,9 +23,9 @@ #include "ipc/ipc_message_macros.h" #include "net/base/request_priority.h" #include "net/cert/signed_certificate_timestamp.h" +#include "net/cert/signed_certificate_timestamp_and_status.h" #include "net/http/http_response_info.h" -#include "net/nqe/network_quality_estimator.h" -#include "net/ssl/signed_certificate_timestamp_and_status.h" +#include "net/nqe/effective_connection_type.h" #include "net/url_request/redirect_info.h" #ifndef CONTENT_COMMON_RESOURCE_MESSAGES_H_ @@ -132,9 +132,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(content::FetchRedirectMode, IPC_ENUM_TRAITS_MAX_VALUE(content::SkipServiceWorker, content::SkipServiceWorker::LAST) -IPC_ENUM_TRAITS_MAX_VALUE( - net::NetworkQualityEstimator::EffectiveConnectionType, - net::NetworkQualityEstimator::EFFECTIVE_CONNECTION_TYPE_LAST - 1) +IPC_ENUM_TRAITS_MAX_VALUE(net::EffectiveConnectionType, + net::EFFECTIVE_CONNECTION_TYPE_LAST - 1) IPC_STRUCT_TRAITS_BEGIN(content::ResourceResponseHead) IPC_STRUCT_TRAITS_PARENT(content::ResourceResponseInfo) @@ -155,21 +154,20 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResourceResponseInfo) IPC_STRUCT_TRAITS_MEMBER(headers) IPC_STRUCT_TRAITS_MEMBER(mime_type) IPC_STRUCT_TRAITS_MEMBER(charset) - IPC_STRUCT_TRAITS_MEMBER(security_info) IPC_STRUCT_TRAITS_MEMBER(has_major_certificate_errors) IPC_STRUCT_TRAITS_MEMBER(content_length) IPC_STRUCT_TRAITS_MEMBER(encoded_data_length) + IPC_STRUCT_TRAITS_MEMBER(encoded_body_length) IPC_STRUCT_TRAITS_MEMBER(appcache_id) IPC_STRUCT_TRAITS_MEMBER(appcache_manifest_url) IPC_STRUCT_TRAITS_MEMBER(load_timing) IPC_STRUCT_TRAITS_MEMBER(devtools_info) IPC_STRUCT_TRAITS_MEMBER(download_file_path) IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_spdy) - IPC_STRUCT_TRAITS_MEMBER(was_npn_negotiated) + IPC_STRUCT_TRAITS_MEMBER(was_alpn_negotiated) IPC_STRUCT_TRAITS_MEMBER(was_alternate_protocol_available) IPC_STRUCT_TRAITS_MEMBER(connection_info) - IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_proxy) - IPC_STRUCT_TRAITS_MEMBER(npn_negotiated_protocol) + IPC_STRUCT_TRAITS_MEMBER(alpn_negotiated_protocol) IPC_STRUCT_TRAITS_MEMBER(socket_address) IPC_STRUCT_TRAITS_MEMBER(was_fetched_via_service_worker) IPC_STRUCT_TRAITS_MEMBER(was_fallback_required_by_service_worker) @@ -179,9 +177,12 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResourceResponseInfo) IPC_STRUCT_TRAITS_MEMBER(service_worker_ready_time) IPC_STRUCT_TRAITS_MEMBER(is_in_cache_storage) IPC_STRUCT_TRAITS_MEMBER(cache_storage_cache_name) - IPC_STRUCT_TRAITS_MEMBER(proxy_server) IPC_STRUCT_TRAITS_MEMBER(is_using_lofi) IPC_STRUCT_TRAITS_MEMBER(effective_connection_type) + IPC_STRUCT_TRAITS_MEMBER(certificate) + IPC_STRUCT_TRAITS_MEMBER(cert_status) + IPC_STRUCT_TRAITS_MEMBER(ssl_connection_status) + IPC_STRUCT_TRAITS_MEMBER(ssl_key_exchange_group) IPC_STRUCT_TRAITS_MEMBER(signed_certificate_timestamps) IPC_STRUCT_TRAITS_MEMBER(cors_exposed_header_names) IPC_STRUCT_TRAITS_END() @@ -213,7 +214,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResourceRequest) IPC_STRUCT_TRAITS_MEMBER(request_initiator) IPC_STRUCT_TRAITS_MEMBER(referrer) IPC_STRUCT_TRAITS_MEMBER(referrer_policy) - IPC_STRUCT_TRAITS_MEMBER(visiblity_state) + IPC_STRUCT_TRAITS_MEMBER(visibility_state) IPC_STRUCT_TRAITS_MEMBER(headers) IPC_STRUCT_TRAITS_MEMBER(load_flags) IPC_STRUCT_TRAITS_MEMBER(origin_pid) @@ -249,6 +250,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResourceRequest) IPC_STRUCT_TRAITS_MEMBER(lofi_state) IPC_STRUCT_TRAITS_MEMBER(resource_body_stream_url) IPC_STRUCT_TRAITS_MEMBER(initiated_in_secure_context) + IPC_STRUCT_TRAITS_MEMBER(download_to_network_cache_only) IPC_STRUCT_TRAITS_END() // Parameters for a ResourceMsg_RequestComplete @@ -256,7 +258,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResourceRequestCompletionStatus) IPC_STRUCT_TRAITS_MEMBER(error_code) IPC_STRUCT_TRAITS_MEMBER(was_ignored_by_handler) IPC_STRUCT_TRAITS_MEMBER(exists_in_cache) - IPC_STRUCT_TRAITS_MEMBER(security_info) IPC_STRUCT_TRAITS_MEMBER(completion_time) IPC_STRUCT_TRAITS_MEMBER(encoded_data_length) IPC_STRUCT_TRAITS_END() @@ -307,19 +308,21 @@ IPC_MESSAGE_CONTROL4(ResourceMsg_SetDataBuffer, // Sent when a chunk of data from a resource request is ready, and the resource // is expected to be small enough to fit in the inlined buffer. // The data is sent as a part of IPC message. -IPC_MESSAGE_CONTROL3(ResourceMsg_InlinedDataChunkReceived, +IPC_MESSAGE_CONTROL4(ResourceMsg_InlinedDataChunkReceived, int /* request_id */, std::vector<char> /* data */, - int /* encoded_data_length */) + int /* encoded_data_length */, + int /* encoded_body_length */) // Sent when some data from a resource request is ready. The data offset and // length specify a byte range into the shared memory buffer provided by the // SetDataBuffer message. -IPC_MESSAGE_CONTROL4(ResourceMsg_DataReceived, +IPC_MESSAGE_CONTROL5(ResourceMsg_DataReceived, int /* request_id */, int /* data_offset */, int /* data_length */, - int /* encoded_data_length */) + int /* encoded_data_length */, + int /* encoded_body_length */) // Sent when some data from a resource request has been downloaded to // file. This is only called in the 'download_to_file' case and replaces diff --git a/chromium/content/common/resource_request.h b/chromium/content/common/resource_request.h index 83263cc5c1c..6e07eef0278 100644 --- a/chromium/content/common/resource_request.h +++ b/chromium/content/common/resource_request.h @@ -34,14 +34,15 @@ struct CONTENT_EXPORT ResourceRequest { // The request method: GET, POST, etc. std::string method; - // The requested URL. + // The absolute requested URL encoded in ASCII per the rules of RFC-2396. GURL url; - // Usually the URL of the document in the top-level window, which may be - // checked by the third-party cookie blocking policy. Leaving it empty may - // lead to undesired cookie blocking. Third-party cookie blocking can be - // bypassed by setting first_party_for_cookies = url, but this should ideally - // only be done if there really is no way to determine the correct value. + // URL representing the first-party origin for the request, which may be + // checked by the third-party cookie blocking policy. This is usually the URL + // of the document in the top-level window. Leaving it empty may lead to + // undesired cookie blocking. Third-party cookie blocking can be bypassed by + // setting first_party_for_cookies = url, but this should ideally only be + // done if there really is no way to determine the correct value. GURL first_party_for_cookies; // The origin of the context which initiated the request, which will be used @@ -54,11 +55,16 @@ struct CONTENT_EXPORT ResourceRequest { // The referrer policy to use. blink::WebReferrerPolicy referrer_policy = blink::WebReferrerPolicyAlways; - // The frame's visiblity state. - blink::WebPageVisibilityState visiblity_state = + // The frame's visibility state. + blink::WebPageVisibilityState visibility_state = blink::WebPageVisibilityStateVisible; // Additional HTTP request headers. + // + // For HTTP(S) requests, the headers parameter can be a \r\n-delimited and + // \r\n-terminated list of MIME headers. They should be ASCII-encoded using + // the standard MIME header encoding rules. The headers parameter can also + // be null if no extra request headers need to be set. std::string headers; // net::URLRequest load flags (0 by default). @@ -72,7 +78,7 @@ struct CONTENT_EXPORT ResourceRequest { // object). ResourceType resource_type = RESOURCE_TYPE_MAIN_FRAME; - // The priority of this request. + // The priority of this request determined by Blink. net::RequestPriority priority = net::IDLE; // Used by plugin->browser requests to get the correct net::URLRequestContext. @@ -116,18 +122,23 @@ struct CONTENT_EXPORT ResourceRequest { // Optional resource request body (may be null). scoped_refptr<ResourceRequestBodyImpl> request_body; + // If true, then the response body will be downloaded to a file and the path + // to that file will be provided in ResponseInfo::download_file_path. bool download_to_file = false; // True if the request was user initiated. bool has_user_gesture = false; + // TODO(mmenke): Investigate if enable_load_timing is safe to remove. + // // True if load timing data should be collected for request. bool enable_load_timing = false; // True if upload progress should be available for request. bool enable_upload_progress = false; - // True if login prompts for this request should be supressed. + // True if login prompts for this request should be supressed. Cached + // credentials or default credentials may still be used for authentication. bool do_not_prompt_for_login = false; // The routing id of the RenderFrame. @@ -173,6 +184,10 @@ struct CONTENT_EXPORT ResourceRequest { // Wether or not the initiator of this request is a secure context. bool initiated_in_secure_context = false; + + // The response should be downloaded and stored in the network cache, but not + // sent back to the renderer. + bool download_to_network_cache_only = false; }; } // namespace content diff --git a/chromium/content/common/resource_request_completion_status.h b/chromium/content/common/resource_request_completion_status.h index 766c0ea2c7d..3ef01cee1f3 100644 --- a/chromium/content/common/resource_request_completion_status.h +++ b/chromium/content/common/resource_request_completion_status.h @@ -28,9 +28,6 @@ struct CONTENT_EXPORT ResourceRequestCompletionStatus { // A copy of the data requested exists in the cache. bool exists_in_cache = false; - // Serialized security info; see content/common/ssl_status_serialization.h. - std::string security_info; - // Time the request completed. base::TimeTicks completion_time; diff --git a/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.cc b/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.cc index 4cd502d8487..bf356017359 100644 --- a/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.cc +++ b/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.cc @@ -13,6 +13,7 @@ #include "build/build_config.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" +#include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h" using sandbox::bpf_dsl::AllOf; using sandbox::bpf_dsl::Allow; @@ -50,7 +51,8 @@ BoolExpr RestrictSocketArguments(const Arg<int>& domain, } // namespace SandboxBPFBasePolicyAndroid::SandboxBPFBasePolicyAndroid() - : SandboxBPFBasePolicy() {} + : SandboxBPFBasePolicy(), + pid_(getpid()) {} SandboxBPFBasePolicyAndroid::~SandboxBPFBasePolicyAndroid() {} @@ -102,6 +104,7 @@ ResultExpr SandboxBPFBasePolicyAndroid::EvaluateSyscall(int sysno) const { #else case __NR_getrlimit: #endif + case __NR_sysinfo: // https://crbug.com/655277 case __NR_uname: // Permit socket operations so that renderers can connect to logd and @@ -122,6 +125,18 @@ ResultExpr SandboxBPFBasePolicyAndroid::EvaluateSyscall(int sysno) const { break; } + // https://crbug.com/644759 + if (sysno == __NR_rt_tgsigqueueinfo) { + const Arg<pid_t> tgid(0); + return If(tgid == pid_, Allow()) + .Else(Error(EPERM)); + } + + // https://crbug.com/655299 + if (sysno == __NR_clock_getres) { + return sandbox::RestrictClockID(); + } + #if defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || \ defined(__mips__) if (sysno == __NR_socket) { diff --git a/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h b/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h index a18c7d44547..79a5d44044b 100644 --- a/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h +++ b/chromium/content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h @@ -5,6 +5,8 @@ #ifndef CONTENT_COMMON_SANDBOX_LINUX_ANDROID_SANDBOX_BPF_BASE_POLICY_ANDROID_H_ #define CONTENT_COMMON_SANDBOX_LINUX_ANDROID_SANDBOX_BPF_BASE_POLICY_ANDROID_H_ +#include <sys/types.h> + #include "base/macros.h" #include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h" @@ -23,6 +25,8 @@ class SandboxBPFBasePolicyAndroid : public SandboxBPFBasePolicy { int system_call_number) const override; private: + const pid_t pid_; + DISALLOW_COPY_AND_ASSIGN(SandboxBPFBasePolicyAndroid); }; diff --git a/chromium/content/common/sandbox_linux/bpf_gpu_policy_linux.cc b/chromium/content/common/sandbox_linux/bpf_gpu_policy_linux.cc index d356897d9e0..47c0bebeecc 100644 --- a/chromium/content/common/sandbox_linux/bpf_gpu_policy_linux.cc +++ b/chromium/content/common/sandbox_linux/bpf_gpu_policy_linux.cc @@ -22,6 +22,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/strings/stringprintf.h" #include "build/build_config.h" #include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h" #include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h" @@ -78,8 +79,8 @@ inline bool IsArchitectureArm() { #endif } -inline bool IsOzone() { -#if defined(USE_OZONE) +inline bool UseV4L2Codec() { +#if defined(USE_V4L2_CODEC) return true; #else return false; @@ -131,18 +132,17 @@ intptr_t GpuSIGSYS_Handler(const struct arch_seccomp_data& args, #endif // !defined(__aarch64__) case __NR_faccessat: if (static_cast<int>(args.args[0]) == AT_FDCWD) { - return - broker_process->Access(reinterpret_cast<const char*>(args.args[1]), - static_cast<int>(args.args[2])); + return broker_process->Access( + reinterpret_cast<const char*>(args.args[1]), + static_cast<int>(args.args[2])); } else { return -EPERM; } case __NR_openat: // Allow using openat() as open(). if (static_cast<int>(args.args[0]) == AT_FDCWD) { - return - broker_process->Open(reinterpret_cast<const char*>(args.args[1]), - static_cast<int>(args.args[2])); + return broker_process->Open(reinterpret_cast<const char*>(args.args[1]), + static_cast<int>(args.args[2])); } else { return -EPERM; } @@ -229,12 +229,10 @@ bool UpdateProcessTypeAndEnableSandbox( } // namespace -GpuProcessPolicy::GpuProcessPolicy() : GpuProcessPolicy(false) { -} +GpuProcessPolicy::GpuProcessPolicy() : GpuProcessPolicy(false) {} GpuProcessPolicy::GpuProcessPolicy(bool allow_mincore) - : broker_process_(NULL), allow_mincore_(allow_mincore) { -} + : broker_process_(NULL), allow_mincore_(allow_mincore) {} GpuProcessPolicy::~GpuProcessPolicy() {} @@ -312,14 +310,14 @@ bool GpuProcessPolicy::PreSandboxHook() { I965DrvVideoPath = "/usr/lib/va/drivers/i965_drv_video.so"; } - dlopen(I965DrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + dlopen(I965DrvVideoPath, RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); if (I965HybridDrvVideoPath) - dlopen(I965HybridDrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); - dlopen("libva.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + dlopen(I965HybridDrvVideoPath, RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); + dlopen("libva.so.1", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); #if defined(USE_OZONE) - dlopen("libva-drm.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + dlopen("libva-drm.so.1", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); #elif defined(USE_X11) - dlopen("libva-x11.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + dlopen("libva-x11.so.1", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); #endif } } @@ -332,6 +330,12 @@ void GpuProcessPolicy::InitGpuBrokerProcess( const std::vector<BrokerFilePermission>& permissions_extra) { static const char kDriRcPath[] = "/etc/drirc"; static const char kDriCard0Path[] = "/dev/dri/card0"; + static const char kDriCardBasePath[] = "/dev/dri/card"; + + static const char kNvidiaCtlPath[] = "/dev/nvidiactl"; + static const char kNvidiaDeviceBasePath[] = "/dev/nvidia"; + static const char kNvidiaParamsPath[] = "/proc/driver/nvidia/params"; + static const char kDevShm[] = "/dev/shm/"; CHECK(broker_process_ == NULL); @@ -340,16 +344,30 @@ void GpuProcessPolicy::InitGpuBrokerProcess( std::vector<BrokerFilePermission> permissions; permissions.push_back(BrokerFilePermission::ReadWrite(kDriCard0Path)); permissions.push_back(BrokerFilePermission::ReadOnly(kDriRcPath)); + if (!IsChromeOS()) { + // For shared memory. permissions.push_back( BrokerFilePermission::ReadWriteCreateUnlinkRecursive(kDevShm)); - } else if (IsArchitectureArm() || IsOzone()){ + // For multi-card DRI setups. NOTE: /dev/dri/card0 was already added above. + for (int i = 1; i <= 9; ++i) { + permissions.push_back(BrokerFilePermission::ReadWrite( + base::StringPrintf("%s%d", kDriCardBasePath, i))); + } + // For Nvidia GLX driver. + permissions.push_back(BrokerFilePermission::ReadWrite(kNvidiaCtlPath)); + for (int i = 0; i <= 9; ++i) { + permissions.push_back(BrokerFilePermission::ReadWrite( + base::StringPrintf("%s%d", kNvidiaDeviceBasePath, i))); + } + permissions.push_back(BrokerFilePermission::ReadOnly(kNvidiaParamsPath)); + } else if (UseV4L2Codec()) { AddV4L2GpuWhitelist(&permissions); if (UseLibV4L2()) { - dlopen("/usr/lib/libv4l2.so", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + dlopen("/usr/lib/libv4l2.so", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); // This is a device-specific encoder plugin. dlopen("/usr/lib/libv4l/plugins/libv4l-encplugin.so", - RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); + RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); } } diff --git a/chromium/content/common/sandbox_mac.mm b/chromium/content/common/sandbox_mac.mm index bd9eb73cbd2..5271dcdd43c 100644 --- a/chromium/content/common/sandbox_mac.mm +++ b/chromium/content/common/sandbox_mac.mm @@ -471,7 +471,7 @@ bool Sandbox::EnableSandbox(int sandbox_type, if (!compiler.InsertStringParam("USER_HOMEDIR_AS_LITERAL", quoted_home_dir)) return false; - bool elcap_or_later = base::mac::IsOSElCapitanOrLater(); + bool elcap_or_later = base::mac::IsAtLeastOS10_11(); if (!compiler.InsertBooleanParam("ELCAP_OR_LATER", elcap_or_later)) return false; diff --git a/chromium/content/common/sandbox_win.cc b/chromium/content/common/sandbox_win.cc index 639e30f9ebc..2cd1e9c32ca 100644 --- a/chromium/content/common/sandbox_win.cc +++ b/chromium/content/common/sandbox_win.cc @@ -31,6 +31,7 @@ #include "base/win/windows_version.h" #include "content/common/content_switches_internal.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/sandbox_init.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" @@ -371,6 +372,12 @@ sandbox::ResultCode AddGenericPolicy(sandbox::TargetPolicy* policy) { return sandbox::SBOX_ALL_OK; } +void LogLaunchWarning(sandbox::ResultCode last_warning, DWORD last_error) { + UMA_HISTOGRAM_SPARSE_SLOWLY("Process.Sandbox.Launch.WarningResultCode", + last_warning); + UMA_HISTOGRAM_SPARSE_SLOWLY("Process.Sandbox.Launch.Warning", last_error); +} + sandbox::ResultCode AddPolicyForSandboxedProcess( sandbox::TargetPolicy* policy) { sandbox::ResultCode result = sandbox::SBOX_ALL_OK; @@ -410,7 +417,9 @@ sandbox::ResultCode AddPolicyForSandboxedProcess( result = policy->SetAlternateDesktop(true); if (result != sandbox::SBOX_ALL_OK) { - // Ignore the result of setting the alternate desktop. + // We ignore the result of setting the alternate desktop, however log + // a launch warning. + LogLaunchWarning(result, ::GetLastError()); DLOG(WARNING) << "Failed to apply desktop security to the renderer"; result = sandbox::SBOX_ALL_OK; } @@ -716,8 +725,10 @@ sandbox::ResultCode StartSandboxedProcess( sandbox::MITIGATION_IMAGE_LOAD_NO_REMOTE | sandbox::MITIGATION_IMAGE_LOAD_NO_LOW_LABEL; - sandbox::ResultCode result = sandbox::SBOX_ERROR_GENERIC; + if (base::FeatureList::IsEnabled(features::kWinSboxDisableExtensionPoints)) + mitigations |= sandbox::MITIGATION_EXTENSION_POINT_DISABLE; + sandbox::ResultCode result = sandbox::SBOX_ERROR_GENERIC; result = policy->SetProcessMitigations(mitigations); if (result != sandbox::SBOX_ALL_OK) @@ -785,12 +796,10 @@ sandbox::ResultCode StartSandboxedProcess( } } -#if !defined(OFFICIAL_BUILD) // If stdout/stderr point to a Windows console, these calls will // have no effect. These calls can fail with SBOX_ERROR_BAD_PARAMS. policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)); policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE)); -#endif if (!delegate->PreSpawnTarget(policy)) return sandbox::SBOX_ERROR_DELEGATE_PRE_SPAWN; @@ -820,9 +829,7 @@ sandbox::ResultCode StartSandboxedProcess( } if (sandbox::SBOX_ALL_OK != last_warning) { - UMA_HISTOGRAM_SPARSE_SLOWLY("Process.Sandbox.Launch.WarningResultCode", - last_warning); - UMA_HISTOGRAM_SPARSE_SLOWLY("Process.Sandbox.Launch.Warning", last_error); + LogLaunchWarning(last_warning, last_error); } delegate->PostSpawnTarget(target.process_handle()); diff --git a/chromium/content/common/security_style_util.cc b/chromium/content/common/security_style_util.cc new file mode 100644 index 00000000000..dcb9eb84fca --- /dev/null +++ b/chromium/content/common/security_style_util.cc @@ -0,0 +1,31 @@ +// 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/common/security_style_util.h" + +#include "url/gurl.h" + +namespace content { + +SecurityStyle GetSecurityStyleForResource( + const GURL& url, + bool has_certificate, + net::CertStatus cert_status) { + // An HTTPS response may not have a certificate for some reason. When that + // happens, use the unauthenticated (HTTP) rather than the authentication + // broken security style so that we can detect this error condition. + if (!url.SchemeIsCryptographic() || !has_certificate) + return SECURITY_STYLE_UNAUTHENTICATED; + + // Minor errors don't lower the security style to + // SECURITY_STYLE_AUTHENTICATION_BROKEN. + if (net::IsCertStatusError(cert_status) && + !net::IsCertStatusMinorError(cert_status)) { + return SECURITY_STYLE_AUTHENTICATION_BROKEN; + } + + return SECURITY_STYLE_AUTHENTICATED; +} + +} // namespace content diff --git a/chromium/content/common/security_style_util.h b/chromium/content/common/security_style_util.h new file mode 100644 index 00000000000..81aa1645a32 --- /dev/null +++ b/chromium/content/common/security_style_util.h @@ -0,0 +1,24 @@ +// 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_COMMON_SECURITY_STYLE_UTIL_H_ +#define CONTENT_COMMON_SECURITY_STYLE_UTIL_H_ + +#include "content/public/common/security_style.h" +#include "net/cert/cert_status_flags.h" + +class GURL; + +namespace content { + +// Returns a security style describing an individual resource. Does +// not take into account any of the page- or host-level state such as +// mixed content or whether the host has run insecure content. +SecurityStyle GetSecurityStyleForResource(const GURL& url, + bool has_certificate, + net::CertStatus cert_status); + +} // namespace content + +#endif // CONTENT_COMMON_SECURITY_STYLE_UTIL_H_ diff --git a/chromium/content/common/mojo/DEPS b/chromium/content/common/service_manager/DEPS index 4aa4defd619..4aa4defd619 100644 --- a/chromium/content/common/mojo/DEPS +++ b/chromium/content/common/service_manager/DEPS diff --git a/chromium/content/common/mojo/OWNERS b/chromium/content/common/service_manager/OWNERS index 9216e7a75ab..9216e7a75ab 100644 --- a/chromium/content/common/mojo/OWNERS +++ b/chromium/content/common/service_manager/OWNERS diff --git a/chromium/content/common/service_manager/child_connection.cc b/chromium/content/common/service_manager/child_connection.cc new file mode 100644 index 00000000000..f21e9c032dd --- /dev/null +++ b/chromium/content/common/service_manager/child_connection.cc @@ -0,0 +1,153 @@ +// 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/service_manager/child_connection.h" + +#include <stdint.h> +#include <utility> + +#include "base/macros.h" +#include "content/public/common/service_manager_connection.h" +#include "mojo/edk/embedder/embedder.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "services/shell/public/cpp/connector.h" +#include "services/shell/public/cpp/identity.h" +#include "services/shell/public/cpp/interface_registry.h" +#include "services/shell/public/interfaces/service.mojom.h" + +namespace content { + +namespace { + +void CallBinderOnTaskRunner( + const shell::InterfaceRegistry::Binder& binder, + scoped_refptr<base::SequencedTaskRunner> task_runner, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle) { + task_runner->PostTask( + FROM_HERE, + base::Bind(binder, interface_name, base::Passed(&request_handle))); +} + +} // namespace + +class ChildConnection::IOThreadContext + : public base::RefCountedThreadSafe<IOThreadContext> { + public: + IOThreadContext() {} + + void Initialize(const shell::Identity& child_identity, + shell::Connector* connector, + mojo::ScopedMessagePipeHandle service_pipe, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) { + DCHECK(!io_task_runner_); + io_task_runner_ = io_task_runner; + std::unique_ptr<shell::Connector> io_thread_connector; + if (connector) + io_thread_connector = connector->Clone(); + io_task_runner_->PostTask( + FROM_HERE, + base::Bind(&IOThreadContext::InitializeOnIOThread, this, + child_identity, + base::Passed(&io_thread_connector), + base::Passed(&service_pipe))); + } + + void ShutDown() { + if (!io_task_runner_) + return; + bool posted = io_task_runner_->PostTask( + FROM_HERE, + base::Bind(&IOThreadContext::ShutDownOnIOThread, this)); + DCHECK(posted); + } + + void GetRemoteInterfaceOnIOThread( + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle) { + if (connection_) { + connection_->GetRemoteInterfaces()->GetInterface( + interface_name, std::move(request_handle)); + } + } + + void SetProcessHandle(base::ProcessHandle handle) { + DCHECK(io_task_runner_); + io_task_runner_->PostTask( + FROM_HERE, + base::Bind(&IOThreadContext::SetProcessHandleOnIOThread, this, handle)); + } + + private: + friend class base::RefCountedThreadSafe<IOThreadContext>; + + virtual ~IOThreadContext() {} + + void InitializeOnIOThread( + const shell::Identity& child_identity, + std::unique_ptr<shell::Connector> connector, + mojo::ScopedMessagePipeHandle service_pipe) { + shell::mojom::ServicePtr service; + service.Bind(mojo::InterfacePtrInfo<shell::mojom::Service>( + std::move(service_pipe), 0u)); + shell::mojom::PIDReceiverRequest pid_receiver_request = + mojo::GetProxy(&pid_receiver_); + + shell::Connector::ConnectParams params(child_identity); + params.set_client_process_connection(std::move(service), + std::move(pid_receiver_request)); + + // In some unit testing scenarios a null connector is passed. + if (connector) + connection_ = connector->Connect(¶ms); + } + + void ShutDownOnIOThread() { + connection_.reset(); + pid_receiver_.reset(); + } + + void SetProcessHandleOnIOThread(base::ProcessHandle handle) { + DCHECK(pid_receiver_.is_bound()); + pid_receiver_->SetPID(base::GetProcId(handle)); + pid_receiver_.reset(); + } + + scoped_refptr<base::SequencedTaskRunner> io_task_runner_; + std::unique_ptr<shell::Connection> connection_; + shell::mojom::PIDReceiverPtr pid_receiver_; + + DISALLOW_COPY_AND_ASSIGN(IOThreadContext); +}; + +ChildConnection::ChildConnection( + const std::string& service_name, + const std::string& instance_id, + const std::string& child_token, + shell::Connector* connector, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) + : context_(new IOThreadContext), + child_identity_(service_name, shell::mojom::kInheritUserID, instance_id), + service_token_(mojo::edk::GenerateRandomToken()), + weak_factory_(this) { + mojo::ScopedMessagePipeHandle service_pipe = + mojo::edk::CreateParentMessagePipe(service_token_, child_token); + + context_->Initialize(child_identity_, connector, std::move(service_pipe), + io_task_runner); + remote_interfaces_.Forward( + base::Bind(&CallBinderOnTaskRunner, + base::Bind(&IOThreadContext::GetRemoteInterfaceOnIOThread, + context_), io_task_runner)); +} + +ChildConnection::~ChildConnection() { + context_->ShutDown(); +} + +void ChildConnection::SetProcessHandle(base::ProcessHandle handle) { + context_->SetProcessHandle(handle); +} + +} // namespace content diff --git a/chromium/content/common/service_manager/child_connection.h b/chromium/content/common/service_manager/child_connection.h new file mode 100644 index 00000000000..f7fc946d330 --- /dev/null +++ b/chromium/content/common/service_manager/child_connection.h @@ -0,0 +1,78 @@ +// 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_COMMON_SERVICE_MANAGER_CHILD_CONNECTION_H_ +#define CONTENT_COMMON_SERVICE_MANAGER_CHILD_CONNECTION_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/process/process_handle.h" +#include "base/sequenced_task_runner.h" +#include "content/common/content_export.h" +#include "services/shell/public/cpp/identity.h" +#include "services/shell/public/cpp/interface_provider.h" +#include "services/shell/public/interfaces/connector.mojom.h" + +namespace shell { +class Connection; +class Connector; +} + +namespace content { + +// Helper class to establish a connection between the shell and a single child +// process. Process hosts can use this when launching new processes which +// should be registered with the service manager. +class CONTENT_EXPORT ChildConnection { + public: + // Prepares a new child connection for a child process which will be + // identified to the service manager as |name|. |instance_id| must be unique + // among all child connections using the same |name|. |connector| is the + // connector to use to establish the connection. + ChildConnection(const std::string& name, + const std::string& instance_id, + const std::string& child_token, + shell::Connector* connector, + scoped_refptr<base::SequencedTaskRunner> io_task_runner); + ~ChildConnection(); + + shell::InterfaceProvider* GetRemoteInterfaces() { + return &remote_interfaces_; + } + + const shell::Identity& child_identity() const { + return child_identity_; + } + + // A token which must be passed to the child process via + // |switches::kPrimordialPipeToken| in order for the child to initialize its + // end of the shell connection pipe. + std::string service_token() const { return service_token_; } + + // Sets the child connection's process handle. This should be called as soon + // as the process has been launched, and the connection will not be fully + // functional until this is called. + void SetProcessHandle(base::ProcessHandle handle); + + private: + class IOThreadContext; + + scoped_refptr<IOThreadContext> context_; + shell::Identity child_identity_; + const std::string service_token_; + + shell::InterfaceProvider remote_interfaces_; + + base::WeakPtrFactory<ChildConnection> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(ChildConnection); +}; + +} // namespace content + +#endif // CONTENT_COMMON_SERVICE_MANAGER_CHILD_CONNECTION_H_ diff --git a/chromium/content/common/mojo/embedded_application_runner.cc b/chromium/content/common/service_manager/embedded_service_runner.cc index f8778d684aa..0a6bbca2e7a 100644 --- a/chromium/content/common/mojo/embedded_application_runner.cc +++ b/chromium/content/common/service_manager/embedded_service_runner.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/mojo/embedded_application_runner.h" +#include "content/common/service_manager/embedded_service_runner.h" #include <vector> @@ -13,80 +13,84 @@ #include "base/threading/thread.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" -#include "services/shell/public/cpp/shell_connection.h" +#include "services/shell/public/cpp/service_context.h" namespace content { -class EmbeddedApplicationRunner::Instance +class EmbeddedServiceRunner::Instance : public base::RefCountedThreadSafe<Instance> { public: Instance(const base::StringPiece& name, - const MojoApplicationInfo& info, + const ServiceInfo& info, const base::Closure& quit_closure) : name_(name.as_string()), - factory_callback_(info.application_factory), - use_own_thread_(!info.application_task_runner && info.use_own_thread), + factory_callback_(info.factory), + use_own_thread_(!info.task_runner && info.use_own_thread), quit_closure_(quit_closure), quit_task_runner_(base::ThreadTaskRunnerHandle::Get()), - application_task_runner_(info.application_task_runner) { - if (!use_own_thread_ && !application_task_runner_) - application_task_runner_ = base::ThreadTaskRunnerHandle::Get(); + task_runner_(info.task_runner) { + if (!use_own_thread_ && !task_runner_) + task_runner_ = base::ThreadTaskRunnerHandle::Get(); } - void BindShellClientRequest(shell::mojom::ShellClientRequest request) { + void BindServiceRequest(shell::mojom::ServiceRequest request) { DCHECK(runner_thread_checker_.CalledOnValidThread()); if (use_own_thread_ && !thread_) { // Start a new thread if necessary. thread_.reset(new base::Thread(name_)); thread_->Start(); - application_task_runner_ = thread_->task_runner(); + task_runner_ = thread_->task_runner(); } - DCHECK(application_task_runner_); - application_task_runner_->PostTask( + DCHECK(task_runner_); + task_runner_->PostTask( FROM_HERE, - base::Bind(&Instance::BindShellClientRequestOnApplicationThread, this, + base::Bind(&Instance::BindServiceRequestOnApplicationThread, this, base::Passed(&request))); } void ShutDown() { DCHECK(runner_thread_checker_.CalledOnValidThread()); - if (thread_) { - application_task_runner_ = nullptr; - thread_.reset(); + if (!task_runner_) + return; + // Any extant ServiceContexts must be destroyed on the application thread. + if (task_runner_->BelongsToCurrentThread()) { + Quit(); + } else { + task_runner_->PostTask(FROM_HERE, + base::Bind(&Instance::Quit, this)); } } private: - void BindShellClientRequestOnApplicationThread( - shell::mojom::ShellClientRequest request) { - DCHECK(application_task_runner_->BelongsToCurrentThread()); + friend class base::RefCountedThreadSafe<Instance>; - if (!shell_client_) { - shell_client_ = factory_callback_.Run( + ~Instance() { + // If this instance had its own thread, it MUST be explicitly destroyed by + // QuitOnRunnerThread() by the time this destructor is run. + DCHECK(!thread_); + } + + void BindServiceRequestOnApplicationThread( + shell::mojom::ServiceRequest request) { + DCHECK(task_runner_->BelongsToCurrentThread()); + + if (!service_) { + service_ = factory_callback_.Run( base::Bind(&Instance::Quit, base::Unretained(this))); } - shell::ShellConnection* new_connection = - new shell::ShellConnection(shell_client_.get(), std::move(request)); + shell::ServiceContext* new_connection = + new shell::ServiceContext(service_.get(), std::move(request)); shell_connections_.push_back(base::WrapUnique(new_connection)); new_connection->SetConnectionLostClosure( - base::Bind(&Instance::OnShellConnectionLost, base::Unretained(this), + base::Bind(&Instance::OnStop, base::Unretained(this), new_connection)); } - private: - friend class base::RefCountedThreadSafe<Instance>; - - ~Instance() { - // If this instance had its own thread, it MUST be explicitly destroyed by - // ShutDown() on the runner's thread by the time this destructor is run. - DCHECK(!thread_); - } - - void OnShellConnectionLost(shell::ShellConnection* connection) { - DCHECK(application_task_runner_->BelongsToCurrentThread()); + void OnStop(shell::ServiceContext* connection) { + DCHECK(task_runner_->BelongsToCurrentThread()); for (auto it = shell_connections_.begin(); it != shell_connections_.end(); ++it) { @@ -98,22 +102,29 @@ class EmbeddedApplicationRunner::Instance } void Quit() { - DCHECK(application_task_runner_->BelongsToCurrentThread()); + DCHECK(task_runner_->BelongsToCurrentThread()); shell_connections_.clear(); - shell_client_.reset(); - quit_task_runner_->PostTask( - FROM_HERE, base::Bind(&Instance::QuitOnRunnerThread, this)); + service_.reset(); + if (quit_task_runner_->BelongsToCurrentThread()) { + QuitOnRunnerThread(); + } else { + quit_task_runner_->PostTask( + FROM_HERE, base::Bind(&Instance::QuitOnRunnerThread, this)); + } } void QuitOnRunnerThread() { DCHECK(runner_thread_checker_.CalledOnValidThread()); - ShutDown(); + if (thread_) { + thread_.reset(); + task_runner_ = nullptr; + } quit_closure_.Run(); } const std::string name_; - const MojoApplicationInfo::ApplicationFactory factory_callback_; + const ServiceInfo::ServiceFactory factory_callback_; const bool use_own_thread_; const base::Closure quit_closure_; const scoped_refptr<base::SingleThreadTaskRunner> quit_task_runner_; @@ -124,41 +135,40 @@ class EmbeddedApplicationRunner::Instance // These fields must only be accessed from the runner's thread. std::unique_ptr<base::Thread> thread_; - scoped_refptr<base::SingleThreadTaskRunner> application_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // These fields must only be accessed from the application thread, except in // the destructor which may run on either the runner thread or the application // thread. - std::unique_ptr<shell::ShellClient> shell_client_; - std::vector<std::unique_ptr<shell::ShellConnection>> shell_connections_; + std::unique_ptr<shell::Service> service_; + std::vector<std::unique_ptr<shell::ServiceContext>> shell_connections_; DISALLOW_COPY_AND_ASSIGN(Instance); }; -EmbeddedApplicationRunner::EmbeddedApplicationRunner( - const base::StringPiece& name, - const MojoApplicationInfo& info) +EmbeddedServiceRunner::EmbeddedServiceRunner(const base::StringPiece& name, + const ServiceInfo& info) : weak_factory_(this) { instance_ = new Instance(name, info, - base::Bind(&EmbeddedApplicationRunner::OnQuit, + base::Bind(&EmbeddedServiceRunner::OnQuit, weak_factory_.GetWeakPtr())); } -EmbeddedApplicationRunner::~EmbeddedApplicationRunner() { +EmbeddedServiceRunner::~EmbeddedServiceRunner() { instance_->ShutDown(); } -void EmbeddedApplicationRunner::BindShellClientRequest( - shell::mojom::ShellClientRequest request) { - instance_->BindShellClientRequest(std::move(request)); +void EmbeddedServiceRunner::BindServiceRequest( + shell::mojom::ServiceRequest request) { + instance_->BindServiceRequest(std::move(request)); } -void EmbeddedApplicationRunner::SetQuitClosure( +void EmbeddedServiceRunner::SetQuitClosure( const base::Closure& quit_closure) { quit_closure_ = quit_closure; } -void EmbeddedApplicationRunner::OnQuit() { +void EmbeddedServiceRunner::OnQuit() { if (!quit_closure_.is_null()) quit_closure_.Run(); } diff --git a/chromium/content/common/service_manager/embedded_service_runner.h b/chromium/content/common/service_manager/embedded_service_runner.h new file mode 100644 index 00000000000..fda29a3cfe8 --- /dev/null +++ b/chromium/content/common/service_manager/embedded_service_runner.h @@ -0,0 +1,63 @@ +// 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_COMMON_SERVICE_MANAGER_EMBEDDED_SERVICE_RUNNER_H_ +#define CONTENT_COMMON_SERVICE_MANAGER_EMBEDDED_SERVICE_RUNNER_H_ + +#include <memory> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" +#include "base/strings/string_piece.h" +#include "content/public/common/service_info.h" +#include "services/shell/public/cpp/service.h" +#include "services/shell/public/interfaces/service.mojom.h" + +namespace content { + +// Hosts an in-process service instance that supports multiple Service +// connections. The first incoming connection will invoke a provided factory +// function to instantiate the service, and the service will automatically be +// torn down when its last connection is lost. The service may be launched and +// torn down multiple times by a single EmbeddedServiceRunner instance. +class EmbeddedServiceRunner { + public: + // Constructs a runner which hosts a service. If an existing instance of the + // service is not running when an incoming connection is made, details from + // |info| will be used to construct a new instance. + EmbeddedServiceRunner(const base::StringPiece& name, + const ServiceInfo& info); + ~EmbeddedServiceRunner(); + + // Binds an incoming ServiceRequest for this service. If the service isn't + // already running, it is started. Otherwise the request is bound to the + // running instance. + void BindServiceRequest(shell::mojom::ServiceRequest request); + + // Sets a callback to run after the service loses its last connection and is + // torn down. + void SetQuitClosure(const base::Closure& quit_closure); + + private: + class Instance; + + void OnQuit(); + + // A reference to the service instance which may operate on the + // |task_runner_|'s thread. + scoped_refptr<Instance> instance_; + + base::Closure quit_closure_; + + base::WeakPtrFactory<EmbeddedServiceRunner> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(EmbeddedServiceRunner); +}; + +} // namespace content + +#endif // CONTENT_COMMON_SERVICE_MANAGER_EMBEDDED_SERVICE_RUNNER_H_ diff --git a/chromium/content/common/service_manager/service_manager_connection_impl.cc b/chromium/content/common/service_manager/service_manager_connection_impl.cc new file mode 100644 index 00000000000..0bc9ac0e0d4 --- /dev/null +++ b/chromium/content/common/service_manager/service_manager_connection_impl.cc @@ -0,0 +1,504 @@ +// 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/common/service_manager/service_manager_connection_impl.h" + +#include <queue> +#include <utility> +#include <vector> + +#include "base/bind.h" +#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 "content/common/service_manager/embedded_service_runner.h" +#include "content/public/common/connection_filter.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "services/shell/public/cpp/service.h" +#include "services/shell/public/cpp/service_context.h" +#include "services/shell/public/interfaces/service_factory.mojom.h" +#include "services/shell/runner/common/client_util.h" + +namespace content { +namespace { + +base::LazyInstance<std::unique_ptr<ServiceManagerConnection>>::Leaky + g_connection_for_process = LAZY_INSTANCE_INITIALIZER; + +ServiceManagerConnection::Factory* service_manager_connection_factory = nullptr; + +} // namespace + +// A ref-counted object which owns the IO thread state of a +// ServiceManagerConnectionImpl. This includes Service and ServiceFactory +// bindings. +class ServiceManagerConnectionImpl::IOThreadContext + : public base::RefCountedThreadSafe<IOThreadContext>, + public shell::Service, + public shell::InterfaceFactory<shell::mojom::ServiceFactory>, + public shell::mojom::ServiceFactory { + public: + using InitializeCallback = base::Callback<void(const shell::Identity&)>; + using ServiceFactoryCallback = + base::Callback<void(shell::mojom::ServiceRequest, const std::string&)>; + + IOThreadContext(shell::mojom::ServiceRequest service_request, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, + std::unique_ptr<shell::Connector> io_thread_connector, + shell::mojom::ConnectorRequest connector_request) + : pending_service_request_(std::move(service_request)), + io_task_runner_(io_task_runner), + io_thread_connector_(std::move(io_thread_connector)), + pending_connector_request_(std::move(connector_request)), + weak_factory_(this) { + // This will be reattached by any of the IO thread functions on first call. + io_thread_checker_.DetachFromThread(); + } + + // Safe to call from any thread. + void Start(const InitializeCallback& initialize_callback, + const ServiceFactoryCallback& create_service_callback, + const base::Closure& stop_callback) { + DCHECK(!started_); + + started_ = true; + callback_task_runner_ = base::ThreadTaskRunnerHandle::Get(); + initialize_handler_ = initialize_callback; + create_service_callback_ = create_service_callback; + stop_callback_ = stop_callback; + io_task_runner_->PostTask( + FROM_HERE, base::Bind(&IOThreadContext::StartOnIOThread, this)); + } + + // Safe to call from whichever thread called Start() (or may have called + // Start()). Must be called before IO thread shutdown. + void ShutDown() { + if (!started_) + return; + + bool posted = io_task_runner_->PostTask( + FROM_HERE, base::Bind(&IOThreadContext::ShutDownOnIOThread, this)); + DCHECK(posted); + } + + // Safe to call any time before a message is received from a process. + // i.e. can be called when starting the process but not afterwards. + int AddConnectionFilter(std::unique_ptr<ConnectionFilter> filter) { + base::AutoLock lock(lock_); + + int id = ++next_filter_id_; + + // We should never hit this in practice, but let's crash just in case. + CHECK_NE(id, kInvalidConnectionFilterId); + + connection_filters_[id] = std::move(filter); + return id; + } + + void RemoveConnectionFilter(int filter_id) { + io_task_runner_->PostTask( + FROM_HERE, + base::Bind(&IOThreadContext::RemoveConnectionFilterOnIOThread, this, + filter_id)); + } + + // Safe to call any time before Start() is called. + void SetDefaultBinderForBrowserConnection( + const shell::InterfaceRegistry::Binder& binder) { + DCHECK(!started_); + default_browser_binder_ = base::Bind( + &IOThreadContext::CallBinderOnTaskRunner, + base::ThreadTaskRunnerHandle::Get(), binder); + } + + private: + friend class base::RefCountedThreadSafe<IOThreadContext>; + + class MessageLoopObserver : public base::MessageLoop::DestructionObserver { + public: + explicit MessageLoopObserver(base::WeakPtr<IOThreadContext> context) + : context_(context) { + base::MessageLoop::current()->AddDestructionObserver(this); + } + + ~MessageLoopObserver() override { + base::MessageLoop::current()->RemoveDestructionObserver(this); + } + + void ShutDown() { + if (!is_active_) + return; + + // The call into |context_| below may reenter ShutDown(), hence we set + // |is_active_| to false here. + is_active_ = false; + if (context_) + context_->ShutDownOnIOThread(); + + delete this; + } + + private: + void WillDestroyCurrentMessageLoop() override { + DCHECK(is_active_); + ShutDown(); + } + + bool is_active_ = true; + base::WeakPtr<IOThreadContext> context_; + + DISALLOW_COPY_AND_ASSIGN(MessageLoopObserver); + }; + + ~IOThreadContext() override {} + + void StartOnIOThread() { + // Should bind |io_thread_checker_| to the context's thread. + DCHECK(io_thread_checker_.CalledOnValidThread()); + service_context_.reset(new shell::ServiceContext( + this, std::move(pending_service_request_), + std::move(io_thread_connector_), + std::move(pending_connector_request_))); + + // MessageLoopObserver owns itself. + message_loop_observer_ = + new MessageLoopObserver(weak_factory_.GetWeakPtr()); + } + + void ShutDownOnIOThread() { + DCHECK(io_thread_checker_.CalledOnValidThread()); + + weak_factory_.InvalidateWeakPtrs(); + + // Note that this method may be invoked by MessageLoopObserver observing + // MessageLoop destruction. In that case, this call to ShutDown is + // effectively a no-op. In any case it's safe. + if (message_loop_observer_) { + message_loop_observer_->ShutDown(); + message_loop_observer_ = nullptr; + } + + // Resetting the ServiceContext below may otherwise release the last + // reference to this IOThreadContext. We keep it alive until the stack + // unwinds. + scoped_refptr<IOThreadContext> keepalive(this); + + factory_bindings_.CloseAllBindings(); + service_context_.reset(); + + ClearConnectionFiltersOnIOThread(); + } + + void ClearConnectionFiltersOnIOThread() { + base::AutoLock lock(lock_); + connection_filters_.clear(); + } + + void RemoveConnectionFilterOnIOThread(int filter_id) { + base::AutoLock lock(lock_); + auto it = connection_filters_.find(filter_id); + DCHECK(it != connection_filters_.end()); + connection_filters_.erase(it); + } + + void OnBrowserConnectionLost() { + DCHECK(io_thread_checker_.CalledOnValidThread()); + has_browser_connection_ = false; + } + + ///////////////////////////////////////////////////////////////////////////// + // shell::Service implementation + + void OnStart(const shell::Identity& identity) override { + DCHECK(io_thread_checker_.CalledOnValidThread()); + DCHECK(!initialize_handler_.is_null()); + id_ = identity; + + InitializeCallback handler = base::ResetAndReturn(&initialize_handler_); + callback_task_runner_->PostTask(FROM_HERE, base::Bind(handler, identity)); + } + + bool OnConnect(const shell::Identity& remote_identity, + shell::InterfaceRegistry* registry) override { + DCHECK(io_thread_checker_.CalledOnValidThread()); + std::string remote_service = remote_identity.name(); + if (remote_service == "service:shell") { + // Only expose the SCF interface to the shell. + registry->AddInterface<shell::mojom::ServiceFactory>(this); + return true; + } + + bool accept = false; + { + base::AutoLock lock(lock_); + for (auto& entry : connection_filters_) { + accept |= entry.second->OnConnect(remote_identity, registry, + service_context_->connector()); + } + } + + if (remote_identity.name() == "service:content_browser" && + !has_browser_connection_) { + has_browser_connection_ = true; + registry->set_default_binder(default_browser_binder_); + registry->SetConnectionLostClosure( + base::Bind(&IOThreadContext::OnBrowserConnectionLost, this)); + return true; + } + + // If no filters were interested, reject the connection. + return accept; + } + + bool OnStop() override { + ClearConnectionFiltersOnIOThread(); + callback_task_runner_->PostTask(FROM_HERE, stop_callback_); + return true; + } + + ///////////////////////////////////////////////////////////////////////////// + // shell::InterfaceFactory<shell::mojom::ServiceFactory> implementation + + void Create(const shell::Identity& remote_identity, + shell::mojom::ServiceFactoryRequest request) override { + DCHECK(io_thread_checker_.CalledOnValidThread()); + factory_bindings_.AddBinding(this, std::move(request)); + } + + ///////////////////////////////////////////////////////////////////////////// + // shell::mojom::ServiceFactory implementation + + void CreateService(shell::mojom::ServiceRequest request, + const std::string& name) override { + DCHECK(io_thread_checker_.CalledOnValidThread()); + callback_task_runner_->PostTask( + FROM_HERE, + base::Bind(create_service_callback_, base::Passed(&request), name)); + } + + static void CallBinderOnTaskRunner( + scoped_refptr<base::SequencedTaskRunner> task_runner, + const shell::InterfaceRegistry::Binder& binder, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle) { + task_runner->PostTask(FROM_HERE, base::Bind(binder, interface_name, + base::Passed(&request_handle))); + } + + base::ThreadChecker io_thread_checker_; + bool started_ = false; + + // Temporary state established on construction and consumed on the IO thread + // once the connection is started. + shell::mojom::ServiceRequest pending_service_request_; + scoped_refptr<base::SequencedTaskRunner> io_task_runner_; + std::unique_ptr<shell::Connector> io_thread_connector_; + shell::mojom::ConnectorRequest pending_connector_request_; + + // TaskRunner on which to run our owner's callbacks, i.e. the ones passed to + // Start(). + scoped_refptr<base::SequencedTaskRunner> callback_task_runner_; + + // Callback to run once Service::OnStart is invoked. + InitializeCallback initialize_handler_; + + // Callback to run when a new Service request is received. + ServiceFactoryCallback create_service_callback_; + + // Callback to run if the service is stopped by the service manager. + base::Closure stop_callback_; + + // Called once a connection has been received from the browser process & the + // default binder (below) has been set up. + bool has_browser_connection_ = false; + + shell::Identity id_; + + // Default binder callback used for the browser connection's + // InterfaceRegistry. + // + // TODO(rockot): Remove this once all interfaces exposed to the browser are + // exposed via a ConnectionFilter. + shell::InterfaceRegistry::Binder default_browser_binder_; + + std::unique_ptr<shell::ServiceContext> service_context_; + mojo::BindingSet<shell::mojom::ServiceFactory> factory_bindings_; + int next_filter_id_ = kInvalidConnectionFilterId; + + // Not owned. + MessageLoopObserver* message_loop_observer_ = nullptr; + + // Guards |connection_filters_|. + base::Lock lock_; + std::map<int, std::unique_ptr<ConnectionFilter>> connection_filters_; + + base::WeakPtrFactory<IOThreadContext> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(IOThreadContext); +}; + +//////////////////////////////////////////////////////////////////////////////// +// ServiceManagerConnection, public: + +// static +void ServiceManagerConnection::SetForProcess( + std::unique_ptr<ServiceManagerConnection> connection) { + DCHECK(!g_connection_for_process.Get()); + g_connection_for_process.Get() = std::move(connection); +} + +// static +ServiceManagerConnection* ServiceManagerConnection::GetForProcess() { + return g_connection_for_process.Get().get(); +} + +// static +void ServiceManagerConnection::DestroyForProcess() { + // This joins the service manager controller thread. + g_connection_for_process.Get().reset(); +} + +// static +void ServiceManagerConnection::SetFactoryForTest(Factory* factory) { + DCHECK(!g_connection_for_process.Get()); + service_manager_connection_factory = factory; +} + +// static +std::unique_ptr<ServiceManagerConnection> ServiceManagerConnection::Create( + shell::mojom::ServiceRequest request, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) { + if (service_manager_connection_factory) + return service_manager_connection_factory->Run(); + return base::MakeUnique<ServiceManagerConnectionImpl>( + std::move(request), io_task_runner); +} + +ServiceManagerConnection::~ServiceManagerConnection() {} + +//////////////////////////////////////////////////////////////////////////////// +// ServiceManagerConnectionImpl, public: + +ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( + shell::mojom::ServiceRequest request, + scoped_refptr<base::SequencedTaskRunner> io_task_runner) + : weak_factory_(this) { + shell::mojom::ConnectorRequest connector_request; + connector_ = shell::Connector::Create(&connector_request); + + std::unique_ptr<shell::Connector> io_thread_connector = connector_->Clone(); + context_ = new IOThreadContext( + std::move(request), io_task_runner, std::move(io_thread_connector), + std::move(connector_request)); +} + +ServiceManagerConnectionImpl::~ServiceManagerConnectionImpl() { + context_->ShutDown(); +} + +//////////////////////////////////////////////////////////////////////////////// +// ServiceManagerConnectionImpl, ServiceManagerConnection implementation: + +void ServiceManagerConnectionImpl::Start() { + context_->Start( + base::Bind(&ServiceManagerConnectionImpl::OnContextInitialized, + weak_factory_.GetWeakPtr()), + base::Bind(&ServiceManagerConnectionImpl::CreateService, + weak_factory_.GetWeakPtr()), + base::Bind(&ServiceManagerConnectionImpl::OnConnectionLost, + weak_factory_.GetWeakPtr())); +} + +void ServiceManagerConnectionImpl::SetInitializeHandler( + const base::Closure& handler) { + DCHECK(initialize_handler_.is_null()); + initialize_handler_ = handler; +} + +shell::Connector* ServiceManagerConnectionImpl::GetConnector() { + return connector_.get(); +} + +const shell::Identity& ServiceManagerConnectionImpl::GetIdentity() const { + return identity_; +} + +void ServiceManagerConnectionImpl::SetConnectionLostClosure( + const base::Closure& closure) { + connection_lost_handler_ = closure; +} + +void ServiceManagerConnectionImpl::SetupInterfaceRequestProxies( + shell::InterfaceRegistry* registry, + shell::InterfaceProvider* provider) { + // It's safe to bind |registry| as a raw pointer because the caller must + // guarantee that it outlives |this|, and |this| is bound as a weak ptr here. + context_->SetDefaultBinderForBrowserConnection( + base::Bind(&ServiceManagerConnectionImpl::GetInterface, + weak_factory_.GetWeakPtr(), registry)); + + // TODO(beng): remove provider parameter. +} + +int ServiceManagerConnectionImpl::AddConnectionFilter( + std::unique_ptr<ConnectionFilter> filter) { + return context_->AddConnectionFilter(std::move(filter)); +} + +void ServiceManagerConnectionImpl::RemoveConnectionFilter(int filter_id) { + context_->RemoveConnectionFilter(filter_id); +} + +void ServiceManagerConnectionImpl::AddEmbeddedService(const std::string& name, + const ServiceInfo& info) { + std::unique_ptr<EmbeddedServiceRunner> service( + new EmbeddedServiceRunner(name, info)); + AddServiceRequestHandler( + name, base::Bind(&EmbeddedServiceRunner::BindServiceRequest, + base::Unretained(service.get()))); + auto result = + embedded_services_.insert(std::make_pair(name, std::move(service))); + DCHECK(result.second); +} + +void ServiceManagerConnectionImpl::AddServiceRequestHandler( + const std::string& name, + const ServiceRequestHandler& handler) { + auto result = request_handlers_.insert(std::make_pair(name, handler)); + DCHECK(result.second); +} + +void ServiceManagerConnectionImpl::CreateService( + shell::mojom::ServiceRequest request, + const std::string& name) { + auto it = request_handlers_.find(name); + if (it != request_handlers_.end()) + it->second.Run(std::move(request)); +} + +void ServiceManagerConnectionImpl::OnContextInitialized( + const shell::Identity& identity) { + identity_ = identity; + if (!initialize_handler_.is_null()) + base::ResetAndReturn(&initialize_handler_).Run(); +} + +void ServiceManagerConnectionImpl::OnConnectionLost() { + if (!connection_lost_handler_.is_null()) + connection_lost_handler_.Run(); +} + +void ServiceManagerConnectionImpl::GetInterface( + shell::mojom::InterfaceProvider* provider, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle) { + provider->GetInterface(interface_name, std::move(request_handle)); +} + +} // namespace content + diff --git a/chromium/content/common/service_manager/service_manager_connection_impl.h b/chromium/content/common/service_manager/service_manager_connection_impl.h new file mode 100644 index 00000000000..4a42331d6ff --- /dev/null +++ b/chromium/content/common/service_manager/service_manager_connection_impl.h @@ -0,0 +1,82 @@ +// 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_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_ +#define CONTENT_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "content/public/common/service_manager_connection.h" +#include "mojo/public/cpp/bindings/string.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "services/shell/public/cpp/identity.h" +#include "services/shell/public/interfaces/service.mojom.h" + +namespace shell { +class Connector; +} + +namespace content { + +class EmbeddedServiceRunner; + +class ServiceManagerConnectionImpl : public ServiceManagerConnection { + public: + explicit ServiceManagerConnectionImpl( + shell::mojom::ServiceRequest request, + scoped_refptr<base::SequencedTaskRunner> io_task_runner); + ~ServiceManagerConnectionImpl() override; + + private: + class IOThreadContext; + + // ServiceManagerConnection: + void Start() override; + void SetInitializeHandler(const base::Closure& handler) override; + shell::Connector* GetConnector() override; + const shell::Identity& GetIdentity() const override; + void SetConnectionLostClosure(const base::Closure& closure) override; + void SetupInterfaceRequestProxies( + shell::InterfaceRegistry* registry, + shell::InterfaceProvider* provider) override; + int AddConnectionFilter(std::unique_ptr<ConnectionFilter> filter) override; + void RemoveConnectionFilter(int filter_id) override; + void AddEmbeddedService(const std::string& name, + const ServiceInfo& info) override; + void AddServiceRequestHandler( + const std::string& name, + const ServiceRequestHandler& handler) override; + + void OnContextInitialized(const shell::Identity& identity); + void OnConnectionLost(); + void CreateService(shell::mojom::ServiceRequest request, + const std::string& name); + void GetInterface(shell::mojom::InterfaceProvider* provider, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle request_handle); + + shell::Identity identity_; + + std::unique_ptr<shell::Connector> connector_; + scoped_refptr<IOThreadContext> context_; + + base::Closure initialize_handler_; + base::Closure connection_lost_handler_; + + std::unordered_map<std::string, std::unique_ptr<EmbeddedServiceRunner>> + embedded_services_; + std::unordered_map<std::string, ServiceRequestHandler> request_handlers_; + + base::WeakPtrFactory<ServiceManagerConnectionImpl> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(ServiceManagerConnectionImpl); +}; + +} // namespace content + +#endif // CONTENT_COMMON_SERVICE_MANAGER_SERVICE_MANAGER_CONNECTION_IMPL_H_ diff --git a/chromium/content/common/service_worker/embedded_worker.mojom b/chromium/content/common/service_worker/embedded_worker.mojom new file mode 100644 index 00000000000..d15d62bb237 --- /dev/null +++ b/chromium/content/common/service_worker/embedded_worker.mojom @@ -0,0 +1,16 @@ +// 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. + +module content.mojom; + +import "services/shell/public/interfaces/interface_provider.mojom"; +import "url/mojo/url.mojom"; + +[Native] +struct EmbeddedWorkerStartParams; + +// Interface to control a renderer-side worker's environment. +interface EmbeddedWorkerInstanceClient { + StartWorker(EmbeddedWorkerStartParams params); +}; diff --git a/chromium/content/common/service_worker/embedded_worker.typemap b/chromium/content/common/service_worker/embedded_worker.typemap new file mode 100644 index 00000000000..664936bb937 --- /dev/null +++ b/chromium/content/common/service_worker/embedded_worker.typemap @@ -0,0 +1,10 @@ +# 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. + +mojom = "//content/common/service_worker/embedded_worker.mojom" +public_headers = + [ "//content/common/service_worker/embedded_worker_start_params.h" ] +traits_headers = + [ "//content/common/service_worker/embedded_worker_messages.h" ] +type_mappings = [ "content.mojom.EmbeddedWorkerStartParams=::content::EmbeddedWorkerStartParams" ] diff --git a/chromium/content/common/service_worker/embedded_worker_messages.h b/chromium/content/common/service_worker/embedded_worker_messages.h index a245c4e0071..34dc1eb2cab 100644 --- a/chromium/content/common/service_worker/embedded_worker_messages.h +++ b/chromium/content/common/service_worker/embedded_worker_messages.h @@ -9,6 +9,7 @@ #include <string> #include "content/common/service_worker/embedded_worker_settings.h" +#include "content/common/service_worker/embedded_worker_start_params.h" #include "content/public/common/console_message_level.h" #include "content/public/common/web_preferences.h" #include "ipc/ipc_message.h" @@ -27,17 +28,17 @@ IPC_STRUCT_TRAITS_BEGIN(content::EmbeddedWorkerSettings) IPC_STRUCT_TRAITS_END() // Parameters structure for EmbeddedWorkerMsg_StartWorker. -IPC_STRUCT_BEGIN(EmbeddedWorkerMsg_StartWorker_Params) - IPC_STRUCT_MEMBER(int, embedded_worker_id) - IPC_STRUCT_MEMBER(int64_t, service_worker_version_id) - IPC_STRUCT_MEMBER(GURL, scope) - IPC_STRUCT_MEMBER(GURL, script_url) - IPC_STRUCT_MEMBER(int, worker_devtools_agent_route_id) - IPC_STRUCT_MEMBER(bool, pause_after_download) - IPC_STRUCT_MEMBER(bool, wait_for_debugger) - IPC_STRUCT_MEMBER(bool, is_installed) - IPC_STRUCT_MEMBER(content::EmbeddedWorkerSettings, settings) -IPC_STRUCT_END() +IPC_STRUCT_TRAITS_BEGIN(content::EmbeddedWorkerStartParams) + IPC_STRUCT_TRAITS_MEMBER(embedded_worker_id) + IPC_STRUCT_TRAITS_MEMBER(service_worker_version_id) + IPC_STRUCT_TRAITS_MEMBER(scope) + IPC_STRUCT_TRAITS_MEMBER(script_url) + IPC_STRUCT_TRAITS_MEMBER(worker_devtools_agent_route_id) + IPC_STRUCT_TRAITS_MEMBER(pause_after_download) + IPC_STRUCT_TRAITS_MEMBER(wait_for_debugger) + IPC_STRUCT_TRAITS_MEMBER(is_installed) + IPC_STRUCT_TRAITS_MEMBER(settings) +IPC_STRUCT_TRAITS_END() // Parameters structure for EmbeddedWorkerHostMsg_ReportConsoleMessage. // The data members directly correspond to parameters of @@ -52,7 +53,7 @@ IPC_STRUCT_END() // Browser -> Renderer message to create a new embedded worker context. IPC_MESSAGE_CONTROL1(EmbeddedWorkerMsg_StartWorker, - EmbeddedWorkerMsg_StartWorker_Params /* params */) + content::EmbeddedWorkerStartParams /* params */) // Browser -> Renderer message to resume a worker that has been started // with the pause_after_download option. diff --git a/chromium/content/common/service_worker/embedded_worker_start_params.cc b/chromium/content/common/service_worker/embedded_worker_start_params.cc new file mode 100644 index 00000000000..93f62ff035e --- /dev/null +++ b/chromium/content/common/service_worker/embedded_worker_start_params.cc @@ -0,0 +1,11 @@ +// 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/common/service_worker/embedded_worker_start_params.h" + +namespace content { + +EmbeddedWorkerStartParams::EmbeddedWorkerStartParams() {} + +} // namespace content diff --git a/chromium/content/common/service_worker/embedded_worker_start_params.h b/chromium/content/common/service_worker/embedded_worker_start_params.h new file mode 100644 index 00000000000..9e2ef2a5b9a --- /dev/null +++ b/chromium/content/common/service_worker/embedded_worker_start_params.h @@ -0,0 +1,30 @@ +// 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/common/content_export.h" +#include "content/common/service_worker/embedded_worker_settings.h" +#include "url/gurl.h" + +#ifndef CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_START_PARAMS_H_ +#define CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_START_PARAMS_H_ + +namespace content { + +struct CONTENT_EXPORT EmbeddedWorkerStartParams { + EmbeddedWorkerStartParams(); + + int embedded_worker_id; + int64_t service_worker_version_id; + GURL scope; + GURL script_url; + int worker_devtools_agent_route_id; + bool pause_after_download; + bool wait_for_debugger; + bool is_installed; + EmbeddedWorkerSettings settings; +}; + +} // namespace content + +#endif // CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_START_PARAMS_H_ diff --git a/chromium/content/common/service_worker/service_worker_messages.h b/chromium/content/common/service_worker/service_worker_messages.h index 6e8c3fe7376..59af129dd12 100644 --- a/chromium/content/common/service_worker/service_worker_messages.h +++ b/chromium/content/common/service_worker/service_worker_messages.h @@ -10,6 +10,7 @@ #include <vector> #include "base/strings/string16.h" +#include "base/time/time.h" #include "content/common/service_worker/service_worker_client_info.h" #include "content/common/service_worker/service_worker_status_code.h" #include "content/common/service_worker/service_worker_types.h" @@ -255,33 +256,41 @@ IPC_MESSAGE_CONTROL3(ServiceWorkerHostMsg_SetVersionId, // Informs the browser that event handling has finished. // Routed to the target ServiceWorkerVersion. -IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_InstallEventFinished, +IPC_MESSAGE_ROUTED4(ServiceWorkerHostMsg_InstallEventFinished, int /* request_id */, blink::WebServiceWorkerEventResult, - bool /* has_fetch_event_handler */) + bool /* has_fetch_event_handler */, + base::Time /* dispatch_event_time */) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_ActivateEventFinished, +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_ActivateEventFinished, int /* request_id */, - blink::WebServiceWorkerEventResult) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_ExtendableMessageEventFinished, + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_ExtendableMessageEventFinished, int /* request_id */, - blink::WebServiceWorkerEventResult) -IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_FetchEventResponse, + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED4(ServiceWorkerHostMsg_FetchEventResponse, int /* response_id */, content::ServiceWorkerFetchEventResult, - content::ServiceWorkerResponse) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_FetchEventFinished, + content::ServiceWorkerResponse, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_FetchEventFinished, int /* event_finish_id */, - blink::WebServiceWorkerEventResult) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_NotificationClickEventFinished, + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_NotificationClickEventFinished, int /* request_id */, - blink::WebServiceWorkerEventResult) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_NotificationCloseEventFinished, + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_NotificationCloseEventFinished, int /* request_id */, - blink::WebServiceWorkerEventResult) -IPC_MESSAGE_ROUTED2(ServiceWorkerHostMsg_PushEventFinished, + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) +IPC_MESSAGE_ROUTED3(ServiceWorkerHostMsg_PushEventFinished, int /* request_id */, - blink::WebServiceWorkerEventResult) + blink::WebServiceWorkerEventResult, + base::Time /* dispatch_event_time */) // Responds to a Ping from the browser. // Routed to the target ServiceWorkerVersion. @@ -488,12 +497,12 @@ IPC_MESSAGE_CONTROL3(ServiceWorkerMsg_FetchEvent, content::ServiceWorkerFetchRequest) IPC_MESSAGE_CONTROL4(ServiceWorkerMsg_NotificationClickEvent, int /* request_id */, - int64_t /* persistent_notification_id */, + std::string /* notification_id */, content::PlatformNotificationData /* notification_data */, int /* action_index */) IPC_MESSAGE_CONTROL3(ServiceWorkerMsg_NotificationCloseEvent, int /* request_id */, - int64_t /* persistent_notification_id */, + std::string /* notification_id */, content::PlatformNotificationData /* notification_data */) IPC_MESSAGE_CONTROL2(ServiceWorkerMsg_PushEvent, int /* request_id */, diff --git a/chromium/content/common/service_worker/service_worker_types.cc b/chromium/content/common/service_worker/service_worker_types.cc index aaa516bf230..2e5bb190e53 100644 --- a/chromium/content/common/service_worker/service_worker_types.cc +++ b/chromium/content/common/service_worker/service_worker_types.cc @@ -55,6 +55,20 @@ ServiceWorkerFetchRequest::ServiceWorkerFetchRequest( ServiceWorkerFetchRequest::~ServiceWorkerFetchRequest() {} +size_t ServiceWorkerFetchRequest::EstimatedStructSize() { + size_t size = sizeof(ServiceWorkerFetchRequest); + size += url.spec().size(); + size += blob_uuid.size(); + size += client_id.size(); + + for (const auto& key_and_value : headers) { + size += key_and_value.first.size(); + size += key_and_value.second.size(); + } + + return size; +} + ServiceWorkerResponse::ServiceWorkerResponse() : status_code(0), response_type(blink::WebServiceWorkerResponseTypeOpaque), @@ -94,6 +108,21 @@ ServiceWorkerResponse::ServiceWorkerResponse( ServiceWorkerResponse::~ServiceWorkerResponse() {} +size_t ServiceWorkerResponse::EstimatedStructSize() { + size_t size = sizeof(ServiceWorkerResponse); + size += url.spec().size(); + size += blob_uuid.size(); + size += stream_url.spec().size(); + size += cache_storage_cache_name.size(); + for (const auto& key_and_value : headers) { + size += key_and_value.first.size(); + size += key_and_value.second.size(); + } + for (const auto& header : cors_exposed_header_names) + size += header.size(); + return size; +} + ServiceWorkerObjectInfo::ServiceWorkerObjectInfo() : handle_id(kInvalidServiceWorkerHandleId), state(blink::WebServiceWorkerStateUnknown), diff --git a/chromium/content/common/service_worker/service_worker_types.h b/chromium/content/common/service_worker/service_worker_types.h index d1196d6755c..4dbe26f8e7e 100644 --- a/chromium/content/common/service_worker/service_worker_types.h +++ b/chromium/content/common/service_worker/service_worker_types.h @@ -146,7 +146,9 @@ struct CONTENT_EXPORT ServiceWorkerFetchRequest { bool is_reload); ServiceWorkerFetchRequest(const ServiceWorkerFetchRequest& other); ~ServiceWorkerFetchRequest(); + size_t EstimatedStructSize(); + // Be sure to update EstimatedSize() when adding members. FetchRequestMode mode; bool is_main_resource_load; RequestContextType request_context_type; @@ -183,7 +185,9 @@ struct CONTENT_EXPORT ServiceWorkerResponse { const ServiceWorkerHeaderList& cors_exposed_header_names); ServiceWorkerResponse(const ServiceWorkerResponse& other); ~ServiceWorkerResponse(); + size_t EstimatedStructSize(); + // Be sure to update EstimatedSize() when adding members. GURL url; int status_code; std::string status_text; diff --git a/chromium/content/common/service_worker/service_worker_utils.cc b/chromium/content/common/service_worker/service_worker_utils.cc index 3a4971fc4ec..fb3e7251f1a 100644 --- a/chromium/content/common/service_worker/service_worker_utils.cc +++ b/chromium/content/common/service_worker/service_worker_utils.cc @@ -6,6 +6,7 @@ #include <string> +#include "base/command_line.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "content/public/common/origin_util.h" @@ -31,11 +32,6 @@ bool PathContainsDisallowedCharacter(const GURL& url) { return false; } -bool AllOriginsMatch(const GURL& url_a, const GURL& url_b, const GURL& url_c) { - return url_a.GetOrigin() == url_b.GetOrigin() && - url_a.GetOrigin() == url_c.GetOrigin(); -} - } // namespace // static @@ -116,12 +112,19 @@ bool ServiceWorkerUtils::CanRegisterServiceWorker(const GURL& context_url, DCHECK(context_url.is_valid()); DCHECK(pattern.is_valid()); DCHECK(script_url.is_valid()); - return AllOriginsMatch(context_url, pattern, script_url) && + return ServiceWorkerUtils::PassOriginEqualitySecurityCheck<GURL>( + context_url, pattern, script_url) && OriginCanAccessServiceWorkers(context_url) && OriginCanAccessServiceWorkers(pattern) && OriginCanAccessServiceWorkers(script_url); } +// static +bool ServiceWorkerUtils::IsMojoForServiceWorkerEnabled() { + return base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kMojoServiceWorker); +} + bool LongestScopeMatcher::MatchLongest(const GURL& scope) { if (!ServiceWorkerUtils::ScopeMatches(scope, url_)) return false; diff --git a/chromium/content/common/service_worker/service_worker_utils.h b/chromium/content/common/service_worker/service_worker_utils.h index 5be59c0aa80..b0c3cc8dee5 100644 --- a/chromium/content/common/service_worker/service_worker_utils.h +++ b/chromium/content/common/service_worker/service_worker_utils.h @@ -5,10 +5,12 @@ #ifndef CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_UTILS_H_ #define CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_UTILS_H_ +#include "base/command_line.h" #include "base/macros.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" +#include "content/public/common/content_switches.h" #include "content/public/common/resource_type.h" #include "url/gurl.h" @@ -44,6 +46,23 @@ class ServiceWorkerUtils { const GURL& pattern, const GURL& script_url); + static bool IsMojoForServiceWorkerEnabled(); + + // Returns true when '--disable-web-security' flag is set. Otherwise returns + // whether the all origins of |urls| are same as the origin of |url|. + template <typename... Args> + static bool PassOriginEqualitySecurityCheck(const GURL& url, + const Args&... urls) { + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kDisableWebSecurity)) + return true; + for (const GURL& u : {urls...}) { + if (url.GetOrigin() != u.GetOrigin()) + return false; + } + return true; + } + // PlzNavigate // Returns true if the |provider_id| was assigned by the browser process. static bool IsBrowserAssignedProviderId(int provider_id) { diff --git a/chromium/content/common/shared_memory_seqlock_buffer.h b/chromium/content/common/shared_memory_seqlock_buffer.h deleted file mode 100644 index cee4f5cb702..00000000000 --- a/chromium/content/common/shared_memory_seqlock_buffer.h +++ /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. - -#ifndef CONTENT_COMMON_SHARED_MEMORY_SEQLOCK_BUFFER_H_ -#define CONTENT_COMMON_SHARED_MEMORY_SEQLOCK_BUFFER_H_ - -#include "content/common/one_writer_seqlock.h" - -namespace content { - -// This structure is stored in shared memory that's shared between the browser -// which does the hardware polling, and the consumers of the data, -// i.e. the renderers. The performance characteristics are that -// we want low latency (so would like to avoid explicit communication via IPC -// between producer and consumer) and relatively large data size. -// -// Writer and reader operate on the same buffer assuming contention is low, and -// contention is detected by using the associated SeqLock. - -template<class Data> -class SharedMemorySeqLockBuffer { - public: - OneWriterSeqLock seqlock; - Data data; -}; - -} // namespace content - -#endif // CONTENT_COMMON_SHARED_MEMORY_SEQLOCK_BUFFER_H_ diff --git a/chromium/content/common/site_isolation_policy.cc b/chromium/content/common/site_isolation_policy.cc index b25741b3b39..4ab845d60b2 100644 --- a/chromium/content/common/site_isolation_policy.cc +++ b/chromium/content/common/site_isolation_policy.cc @@ -6,7 +6,6 @@ #include "base/command_line.h" #include "base/lazy_instance.h" -#include "content/public/common/browser_plugin_guest_mode.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" @@ -18,7 +17,8 @@ bool SiteIsolationPolicy::AreCrossProcessFramesPossible() { return UseDedicatedProcessesForAllSites() || IsTopDocumentIsolationEnabled() || GetContentClient()->IsSupplementarySiteIsolationModeEnabled() || - BrowserPluginGuestMode::UseCrossProcessFramesForGuests(); + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kUseCrossProcessFramesForGuests); } // static @@ -39,10 +39,7 @@ bool SiteIsolationPolicy::IsTopDocumentIsolationEnabled() { // static bool SiteIsolationPolicy::UseSubframeNavigationEntries() { - // Enable the new navigation history behavior if any manner of site isolation - // is active. - // PlzNavigate: also enable the new navigation history behavior. - return AreCrossProcessFramesPossible() || IsBrowserSideNavigationEnabled(); + return true; } } // namespace content diff --git a/chromium/content/common/ssl_status_serialization.cc b/chromium/content/common/ssl_status_serialization.cc deleted file mode 100644 index 96349da3d39..00000000000 --- a/chromium/content/common/ssl_status_serialization.cc +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/ssl_status_serialization.h" - -#include <stdint.h> - -#include "base/logging.h" -#include "base/numerics/safe_conversions.h" -#include "base/pickle.h" - -namespace { - -// Checks that an integer |security_style| is a valid SecurityStyle enum -// value. Returns true if valid, false otherwise. -bool CheckSecurityStyle(int security_style) { - switch (security_style) { - case content::SECURITY_STYLE_UNKNOWN: - case content::SECURITY_STYLE_UNAUTHENTICATED: - case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: - case content::SECURITY_STYLE_WARNING: - case content::SECURITY_STYLE_AUTHENTICATED: - return true; - } - return false; -} - -} // namespace - -namespace content { - -std::string SerializeSecurityInfo(const SSLStatus& ssl_status) { - base::Pickle pickle; - pickle.WriteInt(ssl_status.security_style); - pickle.WriteInt(ssl_status.cert_id); - pickle.WriteUInt32(ssl_status.cert_status); - pickle.WriteInt(ssl_status.security_bits); - pickle.WriteInt(ssl_status.key_exchange_info); - pickle.WriteInt(ssl_status.connection_status); - pickle.WriteUInt32(ssl_status.num_unknown_scts); - pickle.WriteUInt32(ssl_status.num_invalid_scts); - pickle.WriteUInt32(ssl_status.num_valid_scts); - pickle.WriteBool(ssl_status.pkp_bypassed); - return std::string(static_cast<const char*>(pickle.data()), pickle.size()); -} - -bool DeserializeSecurityInfo(const std::string& state, SSLStatus* ssl_status) { - *ssl_status = SSLStatus(); - - if (state.empty()) { - // No SSL used. - return true; - } - - base::Pickle pickle(state.data(), base::checked_cast<int>(state.size())); - base::PickleIterator iter(pickle); - int security_style; - if (!iter.ReadInt(&security_style) || !iter.ReadInt(&ssl_status->cert_id) || - !iter.ReadUInt32(&ssl_status->cert_status) || - !iter.ReadInt(&ssl_status->security_bits) || - !iter.ReadInt(&ssl_status->key_exchange_info) || - !iter.ReadInt(&ssl_status->connection_status) || - !iter.ReadUInt32(&ssl_status->num_unknown_scts) || - !iter.ReadUInt32(&ssl_status->num_invalid_scts) || - !iter.ReadUInt32(&ssl_status->num_valid_scts) || - !iter.ReadBool(&ssl_status->pkp_bypassed)) { - *ssl_status = SSLStatus(); - return false; - } - - if (!CheckSecurityStyle(security_style)) { - *ssl_status = SSLStatus(); - return false; - } - - ssl_status->security_style = static_cast<SecurityStyle>(security_style); - - // Sanity check |security_bits|: the only allowed negative value is -1. - if (ssl_status->security_bits < -1) { - *ssl_status = SSLStatus(); - return false; - } - - // Sanity check |key_exchange_info|: 0 or greater. - if (ssl_status->key_exchange_info < 0) { - *ssl_status = SSLStatus(); - return false; - } - - return true; -} - -} // namespace content diff --git a/chromium/content/common/ssl_status_serialization.h b/chromium/content/common/ssl_status_serialization.h deleted file mode 100644 index ed4062377a5..00000000000 --- a/chromium/content/common/ssl_status_serialization.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_SSL_STATUS_SERIALIZATION_H_ -#define CONTENT_COMMON_SSL_STATUS_SERIALIZATION_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "content/common/content_export.h" -#include "content/public/common/ssl_status.h" - -namespace content { - -// Serializes the given security info. Does NOT include -// |ssl_status.content_status| in the serialized info. -CONTENT_EXPORT std::string SerializeSecurityInfo(const SSLStatus& ssl_status); - -// Deserializes the given security info into |ssl_status|. Note that -// this returns the |content_status| field with its default -// value. Returns true on success and false if the state couldn't be -// deserialized. If false, all fields in |ssl_status| will be set to -// their default values. Note that this function does not validate that -// the deserialized SSLStatus is internally consistent (e.g. that the -// |security_style| matches up with the rest of the fields). -bool CONTENT_EXPORT -DeserializeSecurityInfo(const std::string& state, - SSLStatus* ssl_status) WARN_UNUSED_RESULT; - -} // namespace content - -#endif // CONTENT_COMMON_SSL_STATUS_SERIALIZATION_H_ diff --git a/chromium/content/common/ssl_status_serialization_unittest.cc b/chromium/content/common/ssl_status_serialization_unittest.cc deleted file mode 100644 index d230c329e34..00000000000 --- a/chromium/content/common/ssl_status_serialization_unittest.cc +++ /dev/null @@ -1,112 +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/ssl_status_serialization.h" - -#include "net/ssl/ssl_connection_status_flags.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace content { - -namespace { - -void SetTestStatus(SSLStatus* status) { - status->security_style = SECURITY_STYLE_AUTHENTICATED; - status->cert_id = 1; - status->cert_status = net::CERT_STATUS_DATE_INVALID; - status->security_bits = 80; - status->key_exchange_info = 23; - status->connection_status = net::SSL_CONNECTION_VERSION_TLS1_2; - status->num_unknown_scts = 0; - status->num_invalid_scts = 0; - status->num_valid_scts = 1; -} - -bool SSLStatusAreEqual(const SSLStatus& a, const SSLStatus &b) { - return a.Equals(b); -} - -} // namespace - -std::ostream& operator<<(std::ostream& os, const SSLStatus& status) { - return os << "Security Style: " << status.security_style - << "\nCert ID: " << status.cert_id - << "\nCert Status: " << status.cert_status - << "\nSecurity bits: " << status.security_bits - << "\nKey exchange info: " << status.key_exchange_info - << "\nConnection status: " << status.connection_status - << "\nContent Status: " << status.content_status - << "\nNumber of unknown SCTs: " << status.num_unknown_scts - << "\nNumber of invalid SCTs: " << status.num_invalid_scts - << "\nNumber of valid SCTs: " << status.num_valid_scts; -} - -// Test that a valid serialized SSLStatus returns true on -// deserialization and deserializes correctly. -TEST(SSLStatusSerializationTest, DeserializeSerializedStatus) { - // Serialize dummy data and test that it deserializes properly. - SSLStatus status; - SetTestStatus(&status); - std::string serialized = SerializeSecurityInfo(status); - - SSLStatus deserialized; - ASSERT_TRUE(DeserializeSecurityInfo(serialized, &deserialized)); - EXPECT_PRED2(SSLStatusAreEqual, status, deserialized); - // Test that |content_status| has the default (initialized) value. - EXPECT_EQ(SSLStatus::NORMAL_CONTENT, deserialized.content_status); -} - -// Test that an invalid serialized SSLStatus returns false on -// deserialization. -TEST(SSLStatusSerializationTest, DeserializeBogusStatus) { - // Test that a failure to deserialize returns false and returns - // initialized, default data. - SSLStatus invalid_deserialized; - ASSERT_FALSE( - DeserializeSecurityInfo("not an SSLStatus", &invalid_deserialized)); - EXPECT_PRED2(SSLStatusAreEqual, SSLStatus(), invalid_deserialized); -} - -// Serialize a status with a bad |security_bits| value and test that -// deserializing it fails. -TEST(SSLStatusSerializationTest, DeserializeBogusSecurityBits) { - SSLStatus status; - SetTestStatus(&status); - // |security_bits| must be <-1. (-1 means the strength is unknown, and - // |0 means the connection is not encrypted). - status.security_bits = -5; - std::string serialized = SerializeSecurityInfo(status); - - SSLStatus invalid_deserialized; - ASSERT_FALSE(DeserializeSecurityInfo(serialized, &invalid_deserialized)); - EXPECT_PRED2(SSLStatusAreEqual, SSLStatus(), invalid_deserialized); -} - -// Serialize a status with a bad |key_exchange_info| value and test that -// deserializing it fails. -TEST(SSLStatusSerializationTest, DeserializeBogusKeyExchangeInfo) { - SSLStatus status; - SetTestStatus(&status); - status.key_exchange_info = -1; - - SSLStatus invalid_deserialized; - std::string serialized = SerializeSecurityInfo(status); - ASSERT_FALSE(DeserializeSecurityInfo(serialized, &invalid_deserialized)); - EXPECT_PRED2(SSLStatusAreEqual, SSLStatus(), invalid_deserialized); -} - -// Serialize a status with a bad |security_style| value and test that -// deserializing it fails. -TEST(SSLStatusSerializationTest, DeserializeBogusSecurityStyle) { - SSLStatus status; - SetTestStatus(&status); - status.security_style = static_cast<SecurityStyle>(100); - std::string serialized = SerializeSecurityInfo(status); - - SSLStatus invalid_deserialized; - ASSERT_FALSE(DeserializeSecurityInfo(serialized, &invalid_deserialized)); - EXPECT_PRED2(SSLStatusAreEqual, SSLStatus(), invalid_deserialized); -} - -} // namespace diff --git a/chromium/content/common/swapped_out_messages.cc b/chromium/content/common/swapped_out_messages.cc index 718dd08e49a..39ba68fff37 100644 --- a/chromium/content/common/swapped_out_messages.cc +++ b/chromium/content/common/swapped_out_messages.cc @@ -20,6 +20,8 @@ bool SwappedOutMessages::CanSendWhileSwappedOut(const IPC::Message* msg) { // Handled by RenderWidgetHost. case InputHostMsg_HandleInputEvent_ACK::ID: case ViewHostMsg_UpdateRect::ID: + // Handled by RenderWidgetHostView. + case ViewHostMsg_SetNeedsBeginFrames::ID: // Allow targeted navigations while swapped out. case FrameHostMsg_OpenURL::ID: case ViewHostMsg_Focus::ID: @@ -41,7 +43,6 @@ bool SwappedOutMessages::CanSendWhileSwappedOut(const IPC::Message* msg) { case FrameHostMsg_DomOperationResponse::ID: // Input events propagate from parent to child. case FrameHostMsg_ForwardInputEvent::ID: - case FrameHostMsg_InitializeChildFrame::ID: // The browser should always have an accurate mirror of the renderer's // notion of the current page id. case FrameHostMsg_DidAssignPageId::ID: diff --git a/chromium/content/common/typemaps.gni b/chromium/content/common/typemaps.gni new file mode 100644 index 00000000000..3d2d61fd94a --- /dev/null +++ b/chromium/content/common/typemaps.gni @@ -0,0 +1,13 @@ +# 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. + +typemaps = [ + "//content/common/native_types.typemap", + "//content/common/service_worker/embedded_worker.typemap", + "//content/common/url_loader_status.typemap", + "//content/common/url_request.typemap", + "//content/common/url_response_head.typemap", + "//content/common/web_preferences.typemap", + "//content/common/media/media_session.typemap", +] diff --git a/chromium/content/common/url_loader.mojom b/chromium/content/common/url_loader.mojom new file mode 100644 index 00000000000..bdb72581d55 --- /dev/null +++ b/chromium/content/common/url_loader.mojom @@ -0,0 +1,39 @@ +// 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. + +module content.mojom; + +[Native] +struct URLRequest; + +[Native] +struct URLResponseHead; + +[Native] +struct URLLoaderStatus; + +interface URLLoader { + // If the associated request has |auto_follow_redirects| set to false, + // then upon receiving an URLResponse with a non-NULL |redirect_url| field, + // |FollowRedirect| may be called to load the URL indicated by the redirect. + FollowRedirect(); + + // Cancels the request. The service will cancel loading, but there may be some + // time lag and it is possible that the client gets some notification after + // calling this method for a while. + Cancel(); +}; + +interface URLLoaderClient { + // Called when the response head is received. + OnReceiveResponse(URLResponseHead head); + + // Called when the loader starts loading response body. + OnStartLoadingResponseBody(handle<data_pipe_consumer> body); + + // Called when the loading completes. No notification will be dispatched for + // this client after this message arrives. + OnComplete(URLLoaderStatus completion_status); +}; + diff --git a/chromium/content/common/url_loader_factory.mojom b/chromium/content/common/url_loader_factory.mojom new file mode 100644 index 00000000000..0cd0cb872ef --- /dev/null +++ b/chromium/content/common/url_loader_factory.mojom @@ -0,0 +1,19 @@ +// 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. + +module content.mojom; + +import "url_loader.mojom"; + +interface URLLoaderFactory { + // Creats a URLLoader and starts loading with the given |request|. |client|'s + // method will be called when certain events related to that loading + // (e.g., response arrival) happen. |request_id| is for compatibility with + // the existing Chrome IPC. + CreateLoaderAndStart(URLLoader& loader, + int32 routing_id, + int32 request_id, + URLRequest request, + URLLoaderClient client); +};
\ No newline at end of file diff --git a/chromium/content/common/url_loader_status.typemap b/chromium/content/common/url_loader_status.typemap new file mode 100644 index 00000000000..12d4bd38c1c --- /dev/null +++ b/chromium/content/common/url_loader_status.typemap @@ -0,0 +1,14 @@ +# 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. + +mojom = "//content/common/url_loader.mojom" +public_headers = [ "//content/common/resource_request_completion_status.h" ] +traits_headers = [ "//content/common/resource_messages.h" ] +deps = [ + "//content:export", + "//net:net", + "//third_party/WebKit/public:blink_minimal", +] +type_mappings = + [ "content.mojom.URLLoaderStatus=content::ResourceRequestCompletionStatus" ] diff --git a/chromium/content/common/url_request.typemap b/chromium/content/common/url_request.typemap new file mode 100644 index 00000000000..8e46a0b782c --- /dev/null +++ b/chromium/content/common/url_request.typemap @@ -0,0 +1,14 @@ +# 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. + +mojom = "//content/common/url_loader.mojom" +public_headers = [ "//content/common/resource_request.h" ] +traits_headers = [ "//content/common/resource_messages.h" ] +deps = [ + "//content:export", + "//net:net", + "//third_party/WebKit/public:blink_minimal", + "//ui/base", +] +type_mappings = [ "content.mojom.URLRequest=content::ResourceRequest" ] diff --git a/chromium/content/common/url_response_head.typemap b/chromium/content/common/url_response_head.typemap new file mode 100644 index 00000000000..f5c17ce3ae1 --- /dev/null +++ b/chromium/content/common/url_response_head.typemap @@ -0,0 +1,14 @@ +# 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. + +mojom = "//content/common/url_loader.mojom" +public_headers = [ "//content/public/common/resource_response.h" ] +traits_headers = [ "//content/common/resource_messages.h" ] +deps = [ + "//content:export", + "//net:net", + "//third_party/WebKit/public:blink_minimal", +] +type_mappings = + [ "content.mojom.URLResponseHead=content::ResourceResponseHead" ] diff --git a/chromium/content/common/url_schemes.cc b/chromium/content/common/url_schemes.cc index 96f487b2f04..253bfd32bbf 100644 --- a/chromium/content/common/url_schemes.cc +++ b/chromium/content/common/url_schemes.cc @@ -35,6 +35,11 @@ void RegisterContentSchemes(bool lock_schemes) { url::AddStandardScheme(kChromeUIScheme, url::SCHEME_WITHOUT_PORT); url::AddStandardScheme(kGuestScheme, url::SCHEME_WITHOUT_PORT); + url::AddStandardScheme(kHttpSuboriginScheme, url::SCHEME_WITH_PORT); + url::AddReferrerScheme(kHttpSuboriginScheme, url::SCHEME_WITH_PORT); + url::AddStandardScheme(kHttpsSuboriginScheme, url::SCHEME_WITH_PORT); + url::AddReferrerScheme(kHttpsSuboriginScheme, url::SCHEME_WITH_PORT); + for (const url::SchemeWithType& scheme : additional_standard_schemes) url::AddStandardScheme(scheme.scheme, scheme.type); diff --git a/chromium/content/common/user_agent.cc b/chromium/content/common/user_agent.cc index ad9c0013ada..5602261f681 100644 --- a/chromium/content/common/user_agent.cc +++ b/chromium/content/common/user_agent.cc @@ -30,14 +30,6 @@ std::string GetWebKitVersion() { WEBKIT_SVN_REVISION); } -int GetWebKitMajorVersion() { - return WEBKIT_VERSION_MAJOR; -} - -int GetWebKitMinorVersion() { - return WEBKIT_VERSION_MINOR; -} - std::string GetWebKitRevision() { return WEBKIT_SVN_REVISION; } diff --git a/chromium/content/common/video_capture.mojom b/chromium/content/common/video_capture.mojom new file mode 100644 index 00000000000..6b9a08dc91a --- /dev/null +++ b/chromium/content/common/video_capture.mojom @@ -0,0 +1,19 @@ +// 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. + +module content.mojom; + +interface VideoCaptureHost { + // TODO(mcasas): Migrate the rest of the messages, https://crbug.com/651897. + + // Closes the video capture specified by |device_id|. + Stop(int32 device_id); + + // Pauses the video capture specified by |device_id|. + Pause(int32 device_id); + + // Requests that the video capturer send a frame "soon" (e.g., to resolve + // picture loss or quality issues). + RequestRefreshFrame(int32 device_id); +}; diff --git a/chromium/content/common/view_messages.h b/chromium/content/common/view_messages.h index a70cb9c58cb..c40d6484445 100644 --- a/chromium/content/common/view_messages.h +++ b/chromium/content/common/view_messages.h @@ -15,7 +15,6 @@ #include "cc/ipc/cc_param_traits.h" #include "cc/output/begin_frame_args.h" #include "cc/output/compositor_frame.h" -#include "cc/output/compositor_frame_ack.h" #include "cc/resources/shared_bitmap.h" #include "content/common/content_export.h" #include "content/common/content_param_traits.h" @@ -32,6 +31,7 @@ #include "content/public/common/page_zoom.h" #include "content/public/common/referrer.h" #include "content/public/common/renderer_preferences.h" +#include "content/public/common/screen_info.h" #include "content/public/common/three_d_api_types.h" #include "content/public/common/window_container_type.h" #include "ipc/ipc_channel_handle.h" @@ -44,7 +44,6 @@ #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/WebScreenInfo.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" @@ -61,6 +60,8 @@ #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/geometry/vector2d_f.h" +#include "ui/gfx/icc_profile.h" +#include "ui/gfx/ipc/color/gfx_param_traits.h" #include "ui/gfx/ipc/gfx_param_traits.h" #include "ui/gfx/ipc/skia/gfx_skia_param_traits.h" #include "ui/gfx/range/range.h" @@ -93,7 +94,6 @@ IPC_ENUM_TRAITS_MAX_VALUE(blink::WebTextDirection, blink::WebTextDirection::WebTextDirectionLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebDisplayMode, blink::WebDisplayMode::WebDisplayModeLast) -IPC_ENUM_TRAITS_MAX_VALUE(WindowContainerType, WINDOW_CONTAINER_TYPE_MAX_VALUE) IPC_ENUM_TRAITS(content::FaviconURL::IconType) IPC_ENUM_TRAITS(content::MenuItem::Type) IPC_ENUM_TRAITS_MAX_VALUE(content::NavigationGesture, @@ -105,6 +105,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(gfx::FontRenderParams::Hinting, gfx::FontRenderParams::HINTING_MAX) IPC_ENUM_TRAITS_MAX_VALUE(gfx::FontRenderParams::SubpixelRendering, gfx::FontRenderParams::SUBPIXEL_RENDERING_MAX) +IPC_ENUM_TRAITS_MAX_VALUE(content::ScreenOrientationValues, + content::SCREEN_ORIENTATION_VALUES_LAST) IPC_ENUM_TRAITS_MAX_VALUE(content::TapMultipleTargetsStrategy, content::TAP_MULTIPLE_TARGETS_STRATEGY_MAX) IPC_ENUM_TRAITS_MAX_VALUE(content::ThreeDAPIType, @@ -162,15 +164,16 @@ IPC_STRUCT_TRAITS_BEGIN(blink::WebDeviceEmulationParams) IPC_STRUCT_TRAITS_MEMBER(screenOrientationType) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(blink::WebScreenInfo) - IPC_STRUCT_TRAITS_MEMBER(deviceScaleFactor) +IPC_STRUCT_TRAITS_BEGIN(content::ScreenInfo) + IPC_STRUCT_TRAITS_MEMBER(device_scale_factor) + IPC_STRUCT_TRAITS_MEMBER(icc_profile) IPC_STRUCT_TRAITS_MEMBER(depth) - IPC_STRUCT_TRAITS_MEMBER(depthPerComponent) - IPC_STRUCT_TRAITS_MEMBER(isMonochrome) + IPC_STRUCT_TRAITS_MEMBER(depth_per_component) + IPC_STRUCT_TRAITS_MEMBER(is_monochrome) IPC_STRUCT_TRAITS_MEMBER(rect) - IPC_STRUCT_TRAITS_MEMBER(availableRect) - IPC_STRUCT_TRAITS_MEMBER(orientationType) - IPC_STRUCT_TRAITS_MEMBER(orientationAngle) + IPC_STRUCT_TRAITS_MEMBER(available_rect) + IPC_STRUCT_TRAITS_MEMBER(orientation_type) + IPC_STRUCT_TRAITS_MEMBER(orientation_angle) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::ResizeParams) @@ -179,6 +182,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::ResizeParams) IPC_STRUCT_TRAITS_MEMBER(physical_backing_size) IPC_STRUCT_TRAITS_MEMBER(top_controls_shrink_blink_size) IPC_STRUCT_TRAITS_MEMBER(top_controls_height) + IPC_STRUCT_TRAITS_MEMBER(bottom_controls_height) IPC_STRUCT_TRAITS_MEMBER(visible_viewport_size) IPC_STRUCT_TRAITS_MEMBER(resizer_rect) IPC_STRUCT_TRAITS_MEMBER(is_fullscreen_granted) @@ -232,6 +236,8 @@ IPC_STRUCT_TRAITS_BEGIN(content::RendererPreferences) IPC_STRUCT_TRAITS_MEMBER(enable_referrers) IPC_STRUCT_TRAITS_MEMBER(enable_do_not_track) IPC_STRUCT_TRAITS_MEMBER(webrtc_ip_handling_policy) + IPC_STRUCT_TRAITS_MEMBER(webrtc_udp_min_port) + IPC_STRUCT_TRAITS_MEMBER(webrtc_udp_max_port) IPC_STRUCT_TRAITS_MEMBER(user_agent_override) IPC_STRUCT_TRAITS_MEMBER(accept_languages) IPC_STRUCT_TRAITS_MEMBER(report_frame_name_changes) @@ -239,7 +245,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::RendererPreferences) IPC_STRUCT_TRAITS_MEMBER(disable_client_blocked_error_page) IPC_STRUCT_TRAITS_MEMBER(plugin_fullscreen_allowed) IPC_STRUCT_TRAITS_MEMBER(use_video_overlay_for_embedded_encrypted_video) - IPC_STRUCT_TRAITS_MEMBER(use_view_overlay_for_all_video) IPC_STRUCT_TRAITS_MEMBER(network_contry_iso) #if defined(OS_WIN) IPC_STRUCT_TRAITS_MEMBER(caption_font_family_name) @@ -281,74 +286,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::TextInputState) IPC_STRUCT_TRAITS_MEMBER(is_non_ime_change) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_BEGIN(ViewHostMsg_CreateWindow_Params) - // Routing ID of the view initiating the open. - IPC_STRUCT_MEMBER(int, opener_id) - - // True if this open request came in the context of a user gesture. - IPC_STRUCT_MEMBER(bool, user_gesture) - - // Type of window requested. - IPC_STRUCT_MEMBER(WindowContainerType, window_container_type) - - // The session storage namespace ID this view should use. - IPC_STRUCT_MEMBER(int64_t, session_storage_namespace_id) - - // The name of the resulting frame that should be created (empty if none - // has been specified). UTF8 encoded string. - IPC_STRUCT_MEMBER(std::string, frame_name) - - // The routing id of the frame initiating the open. - IPC_STRUCT_MEMBER(int, opener_render_frame_id) - - // The URL of the frame initiating the open. - IPC_STRUCT_MEMBER(GURL, opener_url) - - // The URL of the top frame containing the opener. - IPC_STRUCT_MEMBER(GURL, opener_top_level_frame_url) - - // The security origin of the frame initiating the open. - IPC_STRUCT_MEMBER(GURL, opener_security_origin) - - // Whether the opener will be suppressed in the new window, in which case - // scripting the new window is not allowed. - IPC_STRUCT_MEMBER(bool, opener_suppressed) - - // Whether the window should be opened in the foreground, background, etc. - IPC_STRUCT_MEMBER(WindowOpenDisposition, disposition) - - // The URL that will be loaded in the new window (empty if none has been - // sepcified). - IPC_STRUCT_MEMBER(GURL, target_url) - - // The referrer that will be used to load |target_url| (empty if none has - // been specified). - IPC_STRUCT_MEMBER(content::Referrer, referrer) - - // The window features to use for the new view. - IPC_STRUCT_MEMBER(blink::WebWindowFeatures, features) - - // The additional window features to use for the new view. We pass these - // separately from |features| above because we cannot serialize WebStrings - // over IPC. - IPC_STRUCT_MEMBER(std::vector<base::string16>, additional_features) -IPC_STRUCT_END() - -IPC_STRUCT_BEGIN(ViewHostMsg_CreateWindow_Reply) - // The ID of the view to be created. If the ID is MSG_ROUTING_NONE, then the - // view couldn't be created. - IPC_STRUCT_MEMBER(int32_t, route_id, MSG_ROUTING_NONE) - - // The ID of the main frame hosted in the view. - IPC_STRUCT_MEMBER(int32_t, main_frame_route_id, MSG_ROUTING_NONE) - - // The ID of the widget for the main frame. - IPC_STRUCT_MEMBER(int32_t, main_frame_widget_route_id, MSG_ROUTING_NONE) - - // TODO(dcheng): No clue. This is kind of duplicated from ViewMsg_New_Params. - IPC_STRUCT_MEMBER(int64_t, cloned_session_storage_namespace_id) -IPC_STRUCT_END() - IPC_STRUCT_BEGIN(ViewHostMsg_CreateWorker_Params) // URL for the worker script. IPC_STRUCT_MEMBER(GURL, url) @@ -425,75 +362,6 @@ IPC_STRUCT_BEGIN(ViewHostMsg_UpdateRect_Params) IPC_STRUCT_MEMBER(int, flags) IPC_STRUCT_END() -IPC_STRUCT_BEGIN(ViewMsg_New_Params) - // Renderer-wide preferences. - IPC_STRUCT_MEMBER(content::RendererPreferences, renderer_preferences) - - // Preferences for this view. - IPC_STRUCT_MEMBER(content::WebPreferences, web_preferences) - - // The ID of the view to be created. - IPC_STRUCT_MEMBER(int32_t, view_id, MSG_ROUTING_NONE) - - // The ID of the main frame hosted in the view. - IPC_STRUCT_MEMBER(int32_t, main_frame_routing_id, MSG_ROUTING_NONE) - - // The ID of the widget for the main frame. - IPC_STRUCT_MEMBER(int32_t, main_frame_widget_routing_id, MSG_ROUTING_NONE) - - // The session storage namespace ID this view should use. - IPC_STRUCT_MEMBER(int64_t, session_storage_namespace_id) - - // The route ID of the opener RenderFrame or RenderFrameProxy, if we need to - // set one (MSG_ROUTING_NONE otherwise). - IPC_STRUCT_MEMBER(int, opener_frame_route_id, MSG_ROUTING_NONE) - - // Whether the RenderView should initially be swapped out. - IPC_STRUCT_MEMBER(bool, swapped_out) - - // Carries replicated information, such as frame name and sandbox flags, for - // this view's main frame, which will be a proxy in |swapped_out| - // views when in --site-per-process mode, or a RenderFrame in all other - // cases. - IPC_STRUCT_MEMBER(content::FrameReplicationState, replicated_frame_state) - - // The ID of the proxy object for the main frame in this view. It is only - // used if |swapped_out| is true. - IPC_STRUCT_MEMBER(int32_t, proxy_routing_id, MSG_ROUTING_NONE) - - // Whether the RenderView should initially be hidden. - IPC_STRUCT_MEMBER(bool, hidden) - - // Whether the RenderView will never be visible. - IPC_STRUCT_MEMBER(bool, never_visible) - - // Whether the window associated with this view was created with an opener. - IPC_STRUCT_MEMBER(bool, window_was_created_with_opener) - - // The initial page ID to use for this view, which must be larger than any - // existing navigation that might be loaded in the view. Page IDs are unique - // to a view and are only updated by the renderer after this initial value. - IPC_STRUCT_MEMBER(int32_t, next_page_id) - - // The initial renderer size. - IPC_STRUCT_MEMBER(content::ResizeParams, initial_size) - - // Whether to enable auto-resize. - IPC_STRUCT_MEMBER(bool, enable_auto_resize) - - // The minimum size to layout the page if auto-resize is enabled. - IPC_STRUCT_MEMBER(gfx::Size, min_size) - - // The maximum size to layout the page if auto-resize is enabled. - IPC_STRUCT_MEMBER(gfx::Size, max_size) - - // The page zoom level. - IPC_STRUCT_MEMBER(double, page_zoom_level) - - // The color profile to use for image decode. - IPC_STRUCT_MEMBER(std::vector<char>, image_decode_color_profile) -IPC_STRUCT_END() - #if defined(OS_MACOSX) IPC_STRUCT_BEGIN(ViewMsg_UpdateScrollbarTheme_Params) IPC_STRUCT_MEMBER(float, initial_button_delay) @@ -525,25 +393,6 @@ IPC_MESSAGE_ROUTED1(ViewMsg_LockMouse_ACK, // Tells the render side that the mouse has been unlocked. IPC_MESSAGE_ROUTED0(ViewMsg_MouseLockLost) -// Sent by the browser when the parameters for vsync alignment have changed. -IPC_MESSAGE_ROUTED2(ViewMsg_UpdateVSyncParameters, - base::TimeTicks /* timebase */, - base::TimeDelta /* interval */) - -// Sent when the history is altered outside of navigation. The history list was -// reset to |history_length| length, and the offset was reset to be -// |history_offset|. -IPC_MESSAGE_ROUTED2(ViewMsg_SetHistoryOffsetAndLength, - int /* history_offset */, - int /* history_length */) - -// Tells the renderer to create a new view. -// This message is slightly different, the view it takes (via -// ViewMsg_New_Params) is the view to create, the message itself is sent as a -// non-view control message. -IPC_MESSAGE_CONTROL1(ViewMsg_New, - ViewMsg_New_Params) - // Sends updated preferences to the renderer. IPC_MESSAGE_ROUTED1(ViewMsg_SetRendererPrefs, content::RendererPreferences) @@ -552,10 +401,6 @@ IPC_MESSAGE_ROUTED1(ViewMsg_SetRendererPrefs, IPC_MESSAGE_ROUTED1(ViewMsg_UpdateWebPreferences, content::WebPreferences) -// Informs the renderer that the timezone has changed along with a new -// timezone ID. -IPC_MESSAGE_CONTROL1(ViewMsg_TimezoneChange, std::string) - // Tells the render view to close. // Expects a Close_ACK message when finished. IPC_MESSAGE_ROUTED0(ViewMsg_Close) @@ -629,13 +474,6 @@ IPC_MESSAGE_ROUTED2(ViewMsg_SetZoomLevelForLoadingURL, GURL /* url */, double /* zoom_level */) -// Change encoding of page in the renderer. -IPC_MESSAGE_ROUTED1(ViewMsg_SetPageEncoding, - std::string /*new encoding name*/) - -// Reset encoding of page in the renderer back to default. -IPC_MESSAGE_ROUTED0(ViewMsg_ResetPageEncodingToDefault) - // Used to tell a render view whether it should expose various bindings // that allow JS content extended privileges. See BindingsPolicy for valid // flag values. @@ -663,9 +501,6 @@ IPC_MESSAGE_ROUTED2(ViewMsg_EnumerateDirectoryResponse, // Expects a ClosePage_ACK message when finished. IPC_MESSAGE_ROUTED0(ViewMsg_ClosePage) -// Notifies the renderer about ui theme changes -IPC_MESSAGE_ROUTED0(ViewMsg_ThemeChanged) - // Notifies the renderer that a paint is to be generated for the rectangle // passed in. IPC_MESSAGE_ROUTED1(ViewMsg_Repaint, @@ -803,29 +638,25 @@ IPC_MESSAGE_ROUTED1(ViewMsg_ExtractSmartClipData, gfx::Rect /* rect */) #endif -// Sent by the browser as a reply to ViewHostMsg_SwapCompositorFrame. -IPC_MESSAGE_ROUTED2(ViewMsg_SwapCompositorFrameAck, - uint32_t /* output_surface_id */, - cc::CompositorFrameAck /* ack */) - // Sent by browser to tell renderer compositor that some resources that were // given to the browser in a swap are not being used anymore. -IPC_MESSAGE_ROUTED2(ViewMsg_ReclaimCompositorResources, - uint32_t /* output_surface_id */, - cc::CompositorFrameAck /* ack */) +// If this message is in response to a swap then is_swap_ack is set. +IPC_MESSAGE_ROUTED3(ViewMsg_ReclaimCompositorResources, + uint32_t /* compositor_frame_sink_id */, + bool /* is_swap_ack */, + cc::ReturnedResourceArray /* resources */) // Sent by browser to give renderer compositor a new namespace ID for any // SurfaceSequences it has to create. -IPC_MESSAGE_ROUTED1(ViewMsg_SetSurfaceIdNamespace, - uint32_t /* surface_id_namespace */) +IPC_MESSAGE_ROUTED1(ViewMsg_SetFrameSinkId, cc::FrameSinkId /* frame_sink_id */) IPC_MESSAGE_ROUTED0(ViewMsg_SelectWordAroundCaret) -// Sent by the browser to ask the renderer to redraw. -// If |request_id| is not zero, it is added to the forced frame's latency info -// as ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT. +// Sent by the browser to ask the renderer to redraw. Robust to events that can +// happen in renderer (abortion of the commit or draw, loss of output surface +// etc.). IPC_MESSAGE_ROUTED1(ViewMsg_ForceRedraw, - int /* request_id */) + ui::LatencyInfo /* latency_info */) // Let renderer know begin frame messages won't be sent even if requested. IPC_MESSAGE_ROUTED1(ViewMsg_SetBeginFramePaused, bool /* paused */) @@ -847,13 +678,6 @@ IPC_MESSAGE_ROUTED1(ViewMsg_HandleCompositorProto, IPC_MESSAGE_ROUTED1(ViewHostMsg_SetNeedsBeginFrames, bool /* enabled */) -// Sent by the renderer when it is creating a new window. The browser creates a -// tab for it. If |reply.route_id| is MSG_ROUTING_NONE, the view couldn't be -// created. -IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_CreateWindow, - ViewHostMsg_CreateWindow_Params, - ViewHostMsg_CreateWindow_Reply) - // Similar to ViewHostMsg_CreateWindow, except used for sub-widgets, like // <select> dropdowns. This message is sent to the WebContentsImpl that // contains the widget being created. @@ -868,15 +692,6 @@ IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_CreateFullscreenWidget, int /* opener_id */, int /* route_id */) -// Asks the browser for a unique routing ID. -IPC_SYNC_MESSAGE_CONTROL0_1(ViewHostMsg_GenerateRoutingID, - int /* routing_id */) - -// Asks the browser for the default audio hardware configuration. -IPC_SYNC_MESSAGE_CONTROL0_2(ViewHostMsg_GetAudioHardwareConfig, - media::AudioParameters /* input parameters */, - media::AudioParameters /* output parameters */) - // These three messages are sent to the parent RenderViewHost to display the // page/widget that was created by // CreateWindow/CreateWidget/CreateFullscreenWidget. routing_id @@ -1086,7 +901,7 @@ IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateZoomLimits, IPC_MESSAGE_ROUTED3( ViewHostMsg_SwapCompositorFrame, - uint32_t /* output_surface_id */, + uint32_t /* compositor_frame_sink_id */, cc::CompositorFrame /* frame */, std::vector<IPC::Message> /* messages_to_deliver_with_frame */) diff --git a/chromium/content/common/web_preferences.typemap b/chromium/content/common/web_preferences.typemap new file mode 100644 index 00000000000..c0c800720a6 --- /dev/null +++ b/chromium/content/common/web_preferences.typemap @@ -0,0 +1,8 @@ +# 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. + +mojom = "//content/common/renderer.mojom" +public_headers = [ "//content/public/common/web_preferences.h" ] +traits_headers = [ "//content/public/common/common_param_traits_macros.h" ] +type_mappings = [ "content.mojom.WebPreferences=content::WebPreferences" ] diff --git a/chromium/content/common/webplugininfo_unittest.cc b/chromium/content/common/webplugininfo_unittest.cc index 5661af31486..a0b1b6311ac 100644 --- a/chromium/content/common/webplugininfo_unittest.cc +++ b/chromium/content/common/webplugininfo_unittest.cc @@ -34,7 +34,7 @@ TEST(PluginUtilsTest, VersionExtraction) { }; for (size_t i = 0; i < arraysize(versions); i++) { - Version version; + base::Version version; WebPluginInfo::CreateVersionFromString( base::ASCIIToUTF16(versions[i][0]), &version); diff --git a/chromium/content/common/websocket.cc b/chromium/content/common/websocket.cc deleted file mode 100644 index b1d57611f68..00000000000 --- a/chromium/content/common/websocket.cc +++ /dev/null @@ -1,18 +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/common/websocket.h" - -namespace content { - -WebSocketHandshakeRequest::WebSocketHandshakeRequest() {} - -WebSocketHandshakeRequest::~WebSocketHandshakeRequest() {} - -WebSocketHandshakeResponse::WebSocketHandshakeResponse() - : status_code(0) {} - -WebSocketHandshakeResponse::~WebSocketHandshakeResponse() {} - -} // namespace content diff --git a/chromium/content/common/websocket.h b/chromium/content/common/websocket.h deleted file mode 100644 index 324e9a100d4..00000000000 --- a/chromium/content/common/websocket.h +++ /dev/null @@ -1,64 +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_COMMON_WEBSOCKET_H_ -#define CONTENT_COMMON_WEBSOCKET_H_ - -#include <string> -#include <utility> -#include <vector> - -#include "base/strings/string_split.h" -#include "base/time/time.h" -#include "url/gurl.h" - -namespace content { - -// WebSocket data message types sent between the browser and renderer processes. -enum WebSocketMessageType { - WEB_SOCKET_MESSAGE_TYPE_CONTINUATION = 0x0, - WEB_SOCKET_MESSAGE_TYPE_TEXT = 0x1, - WEB_SOCKET_MESSAGE_TYPE_BINARY = 0x2, - WEB_SOCKET_MESSAGE_TYPE_LAST = WEB_SOCKET_MESSAGE_TYPE_BINARY -}; - -// Opening handshake request information which will be shown in the inspector. -// All string data should be encoded to ASCII in the browser process. -struct WebSocketHandshakeRequest { - WebSocketHandshakeRequest(); - ~WebSocketHandshakeRequest(); - - // The request URL - GURL url; - // Additional HTTP request headers - base::StringPairs headers; - // HTTP request headers raw string - std::string headers_text; - // The time that this request is sent - base::Time request_time; -}; - -// Opening handshake response information which will be shown in the inspector. -// All string data should be encoded to ASCII in the browser process. -struct WebSocketHandshakeResponse { - WebSocketHandshakeResponse(); - ~WebSocketHandshakeResponse(); - - // The request URL - GURL url; - // HTTP status code - int status_code; - // HTTP status text - std::string status_text; - // Additional HTTP response headers - base::StringPairs headers; - // HTTP response headers raw string - std::string headers_text; - // The time that this response arrives - base::Time response_time; -}; - -} // namespace content - -#endif // CONTENT_COMMON_WEBSOCKET_H_ diff --git a/chromium/content/common/websocket_messages.h b/chromium/content/common/websocket_messages.h deleted file mode 100644 index ce250780b9c..00000000000 --- a/chromium/content/common/websocket_messages.h +++ /dev/null @@ -1,201 +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. - -// Multiply-included message file, hence no include guard. - -// This file defines the IPCs for the browser-side implementation of -// WebSockets. -// -// This IPC interface was originally desined based on the WebSocket -// multiplexing draft spec, -// http://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-09. So, -// some of them are given names correspond to the concepts defined in the spec. -// -// A WebSocketBridge object in the renderer and the corresponding WebSocketHost -// object in the browser are associated using an identifier named channel ID. -// The channel id is chosen by the renderer for a new channel. While the -// channel id is unique per-renderer, the browser may have multiple renderers -// using the same channel id. -// -// There're WebSocketDispatcherHost objects for each renderer. Each of -// WebSocketDispatcherHost holds a channel id to WebSocketHost map. -// -// Received messages are routed to the corresponding object by -// WebSocketDispatcher in the renderer and WebSocketDispatcherHost in the -// browser using the channel ID. -// -// The channel ID value is stored in the routing ID member which is available -// when we use the IPC_MESSAGE_ROUTED macro though it's unintended use. - -#include <stdint.h> - -#include <string> -#include <vector> - -#include "content/common/content_export.h" -#include "content/common/websocket.h" -#include "ipc/ipc_message_macros.h" -#include "url/gurl.h" -#include "url/origin.h" - -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT CONTENT_EXPORT -#define IPC_MESSAGE_START WebSocketMsgStart - -IPC_ENUM_TRAITS_MAX_VALUE(content::WebSocketMessageType, - content::WEB_SOCKET_MESSAGE_TYPE_LAST) - -IPC_STRUCT_BEGIN(WebSocketHostMsg_AddChannelRequest_Params) - IPC_STRUCT_MEMBER(GURL, socket_url) - IPC_STRUCT_MEMBER(std::vector<std::string>, requested_protocols) - IPC_STRUCT_MEMBER(url::Origin, origin) - IPC_STRUCT_MEMBER(GURL, first_party_for_cookies) - IPC_STRUCT_MEMBER(std::string, user_agent_override) - IPC_STRUCT_MEMBER(int, render_frame_id) -IPC_STRUCT_END() - -IPC_STRUCT_TRAITS_BEGIN(content::WebSocketHandshakeRequest) - IPC_STRUCT_TRAITS_MEMBER(url) - IPC_STRUCT_TRAITS_MEMBER(headers) - IPC_STRUCT_TRAITS_MEMBER(headers_text) - IPC_STRUCT_TRAITS_MEMBER(request_time) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(content::WebSocketHandshakeResponse) - IPC_STRUCT_TRAITS_MEMBER(url) - IPC_STRUCT_TRAITS_MEMBER(status_code) - IPC_STRUCT_TRAITS_MEMBER(status_text) - IPC_STRUCT_TRAITS_MEMBER(headers) - IPC_STRUCT_TRAITS_MEMBER(headers_text) - IPC_STRUCT_TRAITS_MEMBER(response_time) -IPC_STRUCT_TRAITS_END() - -// WebSocket messages sent from the renderer to the browser. - -// Open new WebSocket connection to |socket_url|. |requested_protocols| is a -// list of tokens identifying sub-protocols the renderer would like to use, as -// described in RFC6455 "Subprotocols Using the WebSocket Protocol". -IPC_MESSAGE_ROUTED1(WebSocketHostMsg_AddChannelRequest, - WebSocketHostMsg_AddChannelRequest_Params) - -// Send a complete binary WebSocket message consisting of the Blob identified by -// |uuid|. The message will be split into frames as necessary. |expected_size| -// must match the browser's idea of the size of the Blob to prevent flow control -// from becoming desynchronised. If it does not match the connection will be -// terminated with a WebSocketMsg_NotifyFailure message. On success, the browser -// will have consumed |expected_size| bytes of flow control send quota and the -// renderer needs to subtract that from its running total of flow control send -// quota. See the design doc at -// https://docs.google.com/document/d/1CDiXB9pBumhFVVfmIn1CRI6v6byxyqWu2urEE9xp714/edit -// SendFrame or SendBlob IPCs must not be sent by the renderer until the -// BlobSendComplete message has been received from the browser. The renderer -// should retain a reference to the Blob until either a BlobSendComplete or -// NotifyFailure IPC is received. -IPC_MESSAGE_ROUTED2(WebSocketHostMsg_SendBlob, - std::string /* uuid */, - uint64_t /* expected_size */) - -// WebSocket messages sent from the browser to the renderer. - -// Respond to an AddChannelRequest. |selected_protocol| is the sub-protocol the -// server selected, or empty if no sub-protocol was selected. |extensions| is -// the list of extensions negotiated for the connection. -IPC_MESSAGE_ROUTED2(WebSocketMsg_AddChannelResponse, - std::string /* selected_protocol */, - std::string /* extensions */) - -// Notify the renderer that the browser has started an opening handshake. -// This message is for showing the request in the inspector and -// can be omitted if the inspector is not active. -IPC_MESSAGE_ROUTED1(WebSocketMsg_NotifyStartOpeningHandshake, - content::WebSocketHandshakeRequest /* request */) - -// Notify the renderer that the browser has finished an opening handshake. -// This message precedes AddChannelResponse. -// This message is for showing the response in the inspector and -// can be omitted if the inspector is not active. -IPC_MESSAGE_ROUTED1(WebSocketMsg_NotifyFinishOpeningHandshake, - content::WebSocketHandshakeResponse /* response */) - -// Notify the renderer that either: -// - the connection open request (WebSocketHostMsg_AddChannelRequest) failed. -// - the browser is required to fail the connection -// (see RFC6455 7.1.7 for details). -// -// When the renderer process receives this messages it does the following: -// 1. Fire an error event. -// 2. Show |message| to the inspector. -// 3. Close the channel immediately uncleanly, as if it received -// DropChannel(was_clean = false, code = 1006, reason = ""). -// |message| will be shown in the inspector and won't be passed to the script. -// TODO(yhirano): Find the way to pass |message| directly to the inspector -// process. -IPC_MESSAGE_ROUTED1(WebSocketMsg_NotifyFailure, - std::string /* message */) - -// Indicates tbat the current Blob has finished sending. The renderer can -// release its reference on the Blob, and may now use SendFrame or SendBlob to -// send more messages. -IPC_MESSAGE_ROUTED0(WebSocketMsg_BlobSendComplete) - -// WebSocket messages that can be sent in either direction. - -// Send a non-control frame to the channel. -// - If the sender is the renderer, it will be sent to the remote server. -// - If the sender is the browser, it comes from the remote server. -// -// - |fin| indicates that this frame is the last in the current message. -// - |type| is the type of the message. On the first frame of a message, it -// must be set to either WEB_SOCKET_MESSAGE_TYPE_TEXT or -// WEB_SOCKET_MESSAGE_TYPE_BINARY. On subsequent frames, it must be set to -// WEB_SOCKET_MESSAGE_TYPE_CONTINUATION, and the type is the same as that of -// the first message. If |type| is WEB_SOCKET_MESSAGE_TYPE_TEXT, then the -// concatenation of the |data| from every frame in the message must be valid -// UTF-8. If |fin| is not set, |data| must be non-empty. -IPC_MESSAGE_ROUTED3(WebSocketMsg_SendFrame, - bool /* fin */, - content::WebSocketMessageType /* type */, - std::vector<char> /* data */) - -// Add |quota| tokens of send quota for the channel. |quota| must be a positive -// integer. Both the browser and the renderer set send quota for the other -// side, and check that quota has not been exceeded when receiving messages. -// Both sides start a new channel with a quota of 0, and must wait for a -// FlowControl message before calling SendFrame. The total available quota on -// one side must never exceed 0x7FFFFFFFFFFFFFFF tokens. -// -// During "blob sending mode", ie. between the renderer sending a -// WebSocketHostMsg_SendBlob IPC and receiving a WebSocketMsg_BlobSendComplete -// IPC, quota is used up in the browser process to send the blob, but -// FlowControl IPCs for that quota are still sent to the renderer. The render -// process needs to take into account that quota equal to the size of the Blob -// has already been used when calculating how much send quota it has left after -// receiving BlobSendComplete. -IPC_MESSAGE_ROUTED1(WebSocketMsg_FlowControl, int64_t /* quota */) - -// Drop the channel. -// -// When sent by the renderer, this will cause a Close message will be sent and -// the TCP/IP connection will be closed. -// -// When sent by the browser, this indicates that a Close has been received, the -// connection was closed, or a network or protocol error occurred. -// -// - |code| is one of the reason codes specified in RFC6455. -// - |reason|, if non-empty, is a UTF-8 encoded string which may be useful for -// debugging but is not necessarily human-readable, as supplied by the server -// in the Close message. -// - If |was_clean| is false on a message from the browser, then the WebSocket -// connection was not closed cleanly. If |was_clean| is false on a message -// from the renderer, then the connection should be closed immediately without -// a closing handshake and the renderer cannot accept any new messages on this -// connection. -IPC_MESSAGE_ROUTED3(WebSocketMsg_DropChannel, - bool /* was_clean */, - unsigned short /* code */, - std::string /* reason */) - -// Notify the renderer that a closing handshake has been initiated by the -// server, so that it can set the Javascript readyState to CLOSING. -IPC_MESSAGE_ROUTED0(WebSocketMsg_NotifyClosing) |